6

我有以下工作的 jQuery shell:

  $('.jq_noSpaces').on('change', function(){
    alert('you changed the value in the box');
  });

我的表单属性是id="username" name="username"

如何使用以下 jQuery 替换功能自动更改从输入字段中删除空格?

str.replace(/\s+/g, '');

谢谢

4

4 回答 4

12

您可以使用以下语法:

$(this).val($(this).val().replace(/\s+/g, ''));

在事件处理程序内部。

于 2013-03-20T20:43:26.320 回答
3

在事件处理程序中替换框的内容

this.value = this.value.replace(/\s+/g, '');
于 2013-03-20T20:43:51.697 回答
2

根本不需要 jQuery ......只要做this.value = this.value.replace(/s+/g, '');

于 2013-03-20T20:44:10.370 回答
0
$('.jq_noSpaces').on('change', function(){
    $(this).val($(this).val().replace(/\s+/g,"")) //thanks @Sushil for the reminder to use the global flag
    alert('you changed the value in the box');
});

或者,就像其他人所说的那样,您根本不需要 jQuery。不过,我还是倾向于使用它。所有真正酷的程序员都会这样做。

于 2013-03-20T20:45:16.793 回答