Sumit Ghosh
Sumit Ghosh

Reputation: 39

How to make some piece of text inside a input field non editable?

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"); 

**Now,When user will edit the remaining two character's he will not be allowed to edit the piece of text "FR".neither he is allowed to delete this text "FR"

by setting

<input type="text" readonly>

it will make the entire input field non editable,I donot want that,I only want to put restriction on editing on first 2 characters.

can anyone give any solution to this???

Upvotes: 2

Views: 2278

Answers (1)

Izaaz Yunus
Izaaz Yunus

Reputation: 2828

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();
    }
});

Fiddle here!

Upvotes: 3

Related Questions