Javascript只在文本框中预定义文本后验证数字

时间:2015-09-21 05:59:08

标签: javascript validation keypress

我尝试使用Javascript在文本框的开头创建一个包含一些只读文本的文本框,然后允许在只读文本后面进行编辑。我需要在readonly文本后只允许10位数字,并需要验证数字。以下是在文本框中具有只读的Javascript代码

var readOnlyLength = $('#field').val().length;
 $('#output').text(readOnlyLength);enter code here
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
    && ((this.selectionStart < readOnlyLength)
    || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
}
});       

1 个答案:

答案 0 :(得分:1)

如果您正在寻找带脚本的解决方案,那么这里是简单的js和RegExp

&#13;
&#13;
var fixedText = function(textbox, label) {
  var num = textbox.value.replace(/\D/g, ''); //non numeric
  num = num.substr(0, 10); //max 10 digits
  textbox.value = label + num;
};
&#13;
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />
&#13;
&#13;
&#13;

简单labelinputscript

&#13;
&#13;
var numeric = function(textbox) {
  var num = textbox.value.replace(/\D/g, '');
  num = num.substr(0, 10);
  textbox.value = num;
};
&#13;
label.partial,
input.partial {
  border: 1px ridge grey;
  margin-bottom: 3px;
}
label.partial {
  border-right: none;
  cursor: text;
}
input.partial {
  border-left: none;
  margin-left: -4px;
  top: -1px;
  position: relative;
}
&#13;
<label for="PostalCode" class='partial'>Postal Code&nbsp;</label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No&nbsp;</label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />
&#13;
&#13;
&#13;