Ryan Taylor Ryan Taylor - 12 days ago 6
Javascript Question

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

I'm trying to use Javascript to make a text box that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. How can I do this in Javascript/jquery?

Answer

Here's an attempt:

Html:

<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />

JavaScript (jQuery):

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

$('#field').on('keypress, keydown', function(event) {
    if ((event.which != 37 && (event.which != 39))
        && ((this.selectionStart < readOnlyLength)
        || ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
        return false;
    }
});

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.

Demo on jsfiddle

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

jsfiddle

Comments