简体   繁体   中英

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM