题
我有一个文本字段用于输入一些序列号代码。我想设置此代码在有人使用 spase 时显示警报。这意味着不允许使用空格,只允许使用减号来分隔此代码。您有解决这个问题的想法吗?我可以使用jquery验证吗?
the correct typing:
135x0001-135x0100
解决方案
为了防止输入元素中出现空格,您可以使用 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;
});
其他提示
短而甜,而不是依赖
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)">
$('.noSpace').keyup(function() {
this.value = this.value.replace(/\s/g,'');
});
<input type="text" name ="textbox" class="noSpace" />
不隶属于 StackOverflow