Toggle readonly attribute in input field

I created a form. Here is the fiddle

By default, all fields are in readonly state. What I need to do is

  • The active text field for editing, when you click the button Edit buttonand the edit button (name and value), should turn into SAVE button.

  • After editing is completed, the user must click on SAVE button, and he must take the first step again, which means that the button will return to its original state, i.e. Editand text fieldsreadonly

It is advisable to look for a jquery solution.

Thanks in advance!

+5
source share
2 answers

Edit . prev - , ro - readonly (true/false).

readonly ! ro (not ro), " , ( , )", prev .

this , ro.

$('[name="Edit"]').on('click', function() {
    var prev = $(this).prev('input'),
        ro   = prev.prop('readonly');
    prev.prop('readonly', !ro).focus();
    $(this).val(ro ? 'Save' : 'Edit');
});

FIDDLE

+6

:

// binds a click-handler to inputs whose `name` attribute is equal to 'Edit':
$('input[name="Edit"]').click(function(){
    // when the input is clicked, it looks to the previous input element
    // that has a `required` attribute, and sets its `readonly` property,
    // the `r` is the current readonly state (true or false)
    $(this).prev('input[required]').prop('readonly',function(i,r){
        // returns the value as the opposite  of what it currently is
        // if readonly is false, then it returns true (and vice-versa)
        return !r;
    });
});

JS Fiddle demo.

button:

$('input[name="Edit"]').click(function(){
    $(this)
    .val(function(i,v){
        return v === 'Edit' ? 'Finished' : 'Edit';
    })
    .prev('input[required]')
    .prop('readonly',function(i,r){
        return !r;
    });
});

JS Fiddle demo.

+4

All Articles