How to prevent a user from removing the first three characters in a text input?


I have a text input, which has three dynamically-generated characters On when page-load; what I want is that when a user enters data in that fieLd the user should be unable to remove that first three characters from the input.

The text input can contain 10 characters in total, three which we generate and 7 entered by the user.

Currently if the user presses backspace he can delete all characters, but I don’t want to allow them to delete the first three characters.

On page-load the script sets three characters in the Lab text input:

<input id="Lab" maxlength="10" name="LabWareId" type="text" value="" class="valid">

$('#Lab').keyup(function () {
  if ($(this).val().length == $(this).attr('maxlength'))


Option 1 : Put the 3 character prefix outside of the input. This is the best from a user experience perspective.

<p>abc <input id="Lab" maxlength="10" name="LabWareId" type="text" class="valid"></p>

Option 2 : Check for backspace keypress and prevent the delete accordingly.

$(document).on('keydown', function (e) {
  if (e.keyCode == 8 && $('#Lab').is(":focus") && $('#Lab').val().length < 4) {

Answered By – Ryan Dantzler

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published