jQuery 如何防止在打字时使用空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3623395/
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
how to prevent using space while typing?
提问by klox
i have one textfield for input some serial number code.i want set this code show alert if someone use spase. it means space is not allowed and just allowed use minus for separate this code. Are you have any idea for resolve this problem? can i use jquery validate?
我有一个用于输入一些序列号代码的文本字段。如果有人使用 spase,我想设置此代码显示警报。这意味着不允许使用空格,只允许使用减号来分隔此代码。你有解决这个问题的想法吗?我可以使用 jquery 验证吗?
the correct typing:
135x0001-135x0100
回答by user113716
To prevent a space in your input element, you could do this using jQuery:
为了防止输入元素中出现空格,您可以使用 jQuery 执行此操作:
Example:http://jsfiddle.net/AQxhT/
示例: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;
});?
回答by Mark Lalor
Short and sweet NOT jQuery dependent
简短而甜蜜,不依赖于 jQuery
function nospaces(t){
if(t.value.match(/\s/g)){
t.value=t.value.replace(/\s/g,'');
}
}
The HTML
HTML
<input type="text" name ="textbox" id="textbox" onkeyup="nospaces(this)">
回答by Nditah
$('.noSpace').keyup(function() {
this.value = this.value.replace(/\s/g,'');
});
<input type="text" name ="textbox" class="noSpace" />