jquery 如何防止在打字时使用空格?

xnifntxz  于 2022-12-18  发布在  jQuery
关注(0)|答案(4)|浏览(244)

我有一个输入一些序列号代码的文本字段。我想设置此代码显示警报,如果有人使用spase。这意味着空间是不允许的,只是允许使用减号分隔此代码。你有解决此问题的任何想法吗?我可以使用jquery validate?

the correct typing:
135x0001-135x0100
dgjrabp2

dgjrabp21#

要防止input元素中出现空格,可以使用jQuery:

示例:http://jsfiddle.net/AQxhT/

​$('input').keypress(function( e ) {
    if(e.which === 32) 
        return false;
})​​​​​;​

$('input').keypress(function( e ) {    
    if(!/[0-9a-zA-Z-]/.test(String.fromCharCode(e.which)))
        return false;
});​
yyhrrdl8

yyhrrdl82#

简短而友好,不依赖于jQuery

function nospaces(t){
  if(t.value.match(/\s/g)){
    t.value=t.value.replace(/\s/g,'');
  }
}

HTML

<input type="text" name ="textbox" id="textbox" onkeyup="nospaces(this)">
ogsagwnx

ogsagwnx3#

$('.noSpace').keyup(function() {
 this.value = this.value.replace(/\s/g,'');
});

<input type="text" name ="textbox" class="noSpace"  />
fwzugrvs

fwzugrvs4#

你可以在onkeypress事件中使用这个js函数。

function AvoidSpace() {
            if (event.keyCode == 32) {
                event.returnValue = false;
                return false;
            }
        }

这里是输入元素(文本框)

<asp:TextBox ID="textbox" onkeypress="return AvoidSpace()" runat="server"></asp:TextBox>

相关问题