我尝试使用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;
}
});
答案 0 :(得分: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;
};
&#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;
简单label
,input
和script
:
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 </label>
<input type="text" onkeyup="numeric(this)" autofocus='' id='PostalCode' class='partial' />
<br/>
<label for="ContactNo" class='partial'>Contact No </label>
<input type="text" onkeyup="numeric(this)" id='ContactNo' class='partial' />
&#13;