如何在 jQuery 中替换部分输入值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4505718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:22:16  来源:igfitidea点击:

How to replace part of an input value in jQuery?

jqueryreplace

提问by WonderBugger

I've been trying to figure out a way to replace part of a string in an inputvalue, but haven't been able to get it working.

我一直试图找出一种方法来替换输入值中的部分字符串,但一直无法使其正常工作。

The input fieldlooks like this:

输入字段如下所示:

<input type="text" value="20,54,26,99" name="ids" />

I've tried:

我试过了:

$('input[name=ids]').val().replace("54,","");

and

var replit = $('input[name=ids]').val();
replit.replace("54,","");
$('input[name=ids]').val(replit);

but neither worked?

但都没有工作?

回答by alex

$('input[name=ids]').val(function(index, value) {
   return value.replace('54,', '');
});

回答by Raphael Isidro

I've just tried this

我刚试过这个

$('#title').val($('#title').val().replace("54,",""))

and it worked so i assume that it's the way you call the element "$('input[name=ids]')", why don't you try using an id selector?

它起作用了,所以我认为这是您调用元素“$('input[name=ids]')”的方式,为什么不尝试使用 id 选择器呢?

$('#ids')

回答by Minh Nguyen

try

尝试

replit = replit.replace("54,","");

回答by Damien-Wright

var replit = $('input[name=ids]').val().replace("54,","");
$('input[name=ids]').val(replit);

hope that helps :)

希望有帮助:)

EDIT: if you want a working example: http://jsfiddle.net/Damien_at_SF/XQQC2/

编辑:如果你想要一个工作示例:http: //jsfiddle.net/Damien_at_SF/XQQC2/

:)

:)

回答by Brownbagger11

I used this method, however I also included a line of code that replaces part of a string.

我使用了这种方法,但是我还包含了一行代码来替换字符串的一部分。

var matval = document.getElementById("MaterialNumber").value;

var matNum = matval.replace("P", "");

document.getElementById("MaterialNumber").value = "";

document.getElementById("MaterialNumber").value = matNum;

Generally I would not have cleared out the field before putting in the new string, but it did not work like that in this case, This might have been caused by the input method being a barcode scanner and set into a function based on a keypress of that said barcode scanner.

通常我不会在输入新字符串之前清除该字段,但在这种情况下它不会像那样工作,这可能是由于输入法是条码扫描仪并设置为基于按键的功能引起的那个说条形码扫描仪。