Nathan Cheval
Nathan Cheval

Reputation: 823

Javascript - Readonly on beginning text input

I have this input with some text (it could be personne or contacts) :

Is it possible to block modification of the first word?

If there is personne or contacts in the input text, prevent the deletion of these from the input field but only allow entry after these words.

Upvotes: 0

Views: 55

Answers (2)

ikiK
ikiK

Reputation: 6532

Here's simple JS solution, you can write in it but can not delete:

document.querySelector('#myInput').addEventListener('keyup', val, false);
function val() {
  if (this.value.includes("personne ") === false) {
    this.value = "personne ";
  }
}
<input type="text" value="personne " size="30" id="myInput">

And you can even make sure if user types something, and selects the personne with mouse and delete it with keyboard, to append it back again with value typed after it:

document.querySelector('#myInput').addEventListener('keyup', val, false);
function val() {
  if (this.value.includes("personne ") === false) {
    this.value = "personne " + this.value.substr(this.value.indexOf(' ') + 1);
    this.value = this.value.replace("personne personne", "personne ");
  }
}
<input type="text" value="personne " size="30" id="myInput">

Upvotes: 1

izik
izik

Reputation: 1043

you can do something like this:

input{
padding-left:70px;
}
.input-container{
position: relative;
}
.input-container:after{
content: 'prersonne';
position:absolute;
top: 50%;
left: 5px;
transform: translateY(-50%);
}
<div class="input-container">
  <input type="text">
</div>

Upvotes: 0

Related Questions