简体   繁体   English

用JQuery / Javascript替换字符串中的所有逗号

[英]Replace all commas in a string with JQuery/Javascript

I have a form where I have a couple hundred text boxes and I'd like to remove any commas when they are loaded and prevent commas from being entered. 我有一个表单,我有几百个文本框,我想在加载时删除任何逗号,并防止输入逗号。 Shouldn't the follow code work assuming the selector is correct? 假设选择器是正确的,跟随代码不应该工作吗?

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value.replace(",", "")
  })
  .onkeyup(function () {
      this.value.replace(",", "") 
  })
});
$(function(){
    $("input[id*=_tb]").each(function(){
        this.value=this.value.replace(/,/g, "");
    }).on('keyup', function(){
        this.value=this.value.replace(/,/g, "");
    });
});

See here for an explanation and examples of the javascript string.replace() function: 有关javascript string.replace()函数的说明和示例,请参见此处:

http://davidwalsh.name/javascript-replace http://davidwalsh.name/javascript-replace

as @Vega said, this doesn't write the new value back to the textbox - I updated the code to do so. 正如@Vega所说,这不会将新值写回文本框 - 我更新了代码来执行此操作。

使用带有g标志的正则表达式而不是字符串: .replace(/,/g, "")

Your code looks right except that it is not setting the value back to the input field, 您的代码看起来正确,只是它没有将值设置回输入字段,

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value = this.value.replace(/,/g, "")
  })
  .onkeyup(function () {
      this.value = this.value.replace(/,/g, "") 
  })
});

Edit: Used regex 编辑:使用正则表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM