如何使输入字段中的某些文本不可编辑? [英] How to make some piece of text inside a input field non editable?

查看:160
本文介绍了如何使输入字段中的某些文本不可编辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段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();
    }
});

小提琴此处

这篇关于如何使输入字段中的某些文本不可编辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆