【问题标题】:Javascript to validate only Numeric after predefined text in a textboxJavascript在文本框中预定义文本后仅验证数字
【发布时间】:2015-09-21 15:13:26
【问题描述】:

我正在尝试使用 Javascript 创建一个文本框,该文本框在文本框的开头包含一些只读文本,然后允许在只读文本之后进行编辑。我只需要在只读文本之后允许 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;
}
});       

【问题讨论】:

  • 您可以通过禁用输入来达到只读状态。
  • 为什么不简单地为固定文本使用标签,为数字输入使用文本框?
  • 只允许 10 位数字是固定的10 还是最大的10
  • 有什么问题?

标签: javascript validation keypress


【解决方案1】:

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

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;
};
<input type="text" onkeyup="fixedText(this, 'Postal Code: ')" autofocus='' value="Postal Code: " />
<input type="text" onkeyup="fixedText(this, 'Contact No: ')" value='Contact No: ' />

用简单的label,inputscript:

var numeric = function(textbox) {
  var num = textbox.value.replace(/\D/g, '');
  num = num.substr(0, 10);
  textbox.value = num;
};
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;
}
<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' />

【讨论】:

    猜你喜欢
    • 2017-05-05
    • 1970-01-01
    • 2012-07-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多