Wednesday, April 11, 2012

Input text field editable and non-editable on button click

jquery makes it simple by just adding and removing the readonly attribute to the text field.

The HTML
<input type="text" value="Edit me" readonly="readonly" />
<input type="button" value="Make Editable" class="makeEditable" />
<input type="button" value="Make Non Editable" class="makeNonEditable" />
The jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
    $(".makeEditable").click(function(){
        $('input:text').removeAttr("readonly");
    });

    $(".makeNonEditable").click(function(){
        $('input:text').attr("readonly", "readonly");
    });
});
</script>
Demo: http://jsfiddle.net/jmuh3yzo/

Another demo that toggles the field: http://jsfiddle.net/aub2x3ka/

No comments:

Post a Comment