如何使输入字段中的某些文本不可编辑?
问题描述:
我有一个输入字段maxLength 4的要求,在这4个字符中,前2个字符将是"FR".其余2个字符将由用户插入.因此,在页面加载期间,我称a jQuery函数,并像这样设置值"FR"
I have a requirement that I have a input field of maxLength 4.among these 4 characters first 2 characters will be "FR".Remaining 2 character will be inserted by user.So,during the page loading time I have called a Jquery Function and set the value "FR" like this
$('.testData').val("FR");
**现在,当用户将编辑其余两个字符时,将不允许他编辑文本"FR" .也不允许他删除此文本"FR" "
通过设置
<input type="text" readonly>
这将使整个输入字段不可编辑,我不希望那样,我只想限制前两个字符的编辑.
任何人都可以对此解决方案吗?
can anyone give any solution to this???
答
hacky解决方案,但使用JS可以解决问题.
A hacky solution, but kinda does the trick using JS.
<input id="myId" type="text" value="AZ"></input>
$("#myId").keydown(function(event){
console.log(this.selectionStart);
console.log(event);
if(event.keyCode == 8){
this.selectionStart--;
}
if(this.selectionStart < 2){
this.selectionStart = 2;
console.log(this.selectionStart);
event.preventDefault();
}
});
$("#myId").keyup(function(event){
console.log(this.selectionStart);
if(this.selectionStart < 2){
this.selectionStart = 2;
console.log(this.selectionStart);
event.preventDefault();
}
});
小提琴此处!