How to make only some text in a text-box read-only while allowing the rest to be edited

Here’s an attempt:

var readOnlyLength = $('#field').val().length;

$('#output').text(readOnlyLength);

$('#field').on('keypress, keydown', function(event) {
  var $field = $(this);
  $('#output').text(event.which + '-' + this.selectionStart);
  if ((event.which != 37 && (event.which != 39)) &&
    ((this.selectionStart < readOnlyLength) ||
      ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
    return false;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />
<div id="output">
</div>

This disables keys other than the left and right arrows for the read-only part. It also disables the backspace key when just at the end of the read-only part.

From what I’ve read, this won’t work on IE <= 8.


Here it is in plain JavaScript (no JQuery):

function makeInitialTextReadOnly(input) {
  var readOnlyLength = input.value.length;
  field.addEventListener('keydown', function(event) {
    var which = event.which;
    if (((which == 8) && (input.selectionStart <= readOnlyLength)) ||
      ((which == 46) && (input.selectionStart < readOnlyLength))) {
      event.preventDefault();
    }
  });
  field.addEventListener('keypress', function(event) {
    var which = event.which;
    if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
      event.preventDefault();
    }
  });
}

makeInitialTextReadOnly(document.getElementById('field'));
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />

Leave a Comment