mtcrts70
mtcrts70

Reputation: 35

HTML input box readonly---javascript button overrides text

Here is a js fiddle example:

http://jsfiddle.net/YD6PL/110/

HTML:

<input type="text" value="a" readonly>
<input type="text">
<input type="text">
<div>
<button class="buttons">c</button>
<button class="buttons">a</button>
<button class="buttons">t</button>
</div>

JS:

$(document).ready(function () {

    $('input').click(function(){
        $(this).addClass('active').siblings('.active').removeClass('active')
    });

    $(".buttons").click(function () {
        var cntrl = $(this).html();
        $('input.active').val(cntrl);
    });
});

The readonly attribute works when the user uses the keyboard to try and input something over the 'a' in the above example. But when the user clicks a button to insert text it seems to trump the readonly attribute and replaces the text. How can I prevent this from happening so that it is always read only.

Upvotes: 0

Views: 161

Answers (2)

imtheman
imtheman

Reputation: 4843

If you don't want the buttons to change readonly inputs, you can change the jQuery selector to this:

$('input.active:not([readonly])').val(cntrl);

JSFiddle

Upvotes: 1

David Routen
David Routen

Reputation: 349

You should use disabled instead of readonly. That works in this updated fiddle. http://jsfiddle.net/YD6PL/110/. This will prevent the user from selecting the box so they won't be able to change it. Not sure if they need to be able to highlight the text in there as well, but try this first!

Upvotes: 0

Related Questions