Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle readonly attribute in input field

I have created a form. Here is the fiddle

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

  1. Active the text field to edit when use click on the Edit button and edit button (Name and value) should turn into SAVE button.

  2. Once editing is done user should click on the Save button and it should do the first step again, means change the button back to the original state i.e Edit and text fields to readonly

preferably looking for jquery solution.

Thank in advance!!

like image 709
Sowmya Avatar asked Mar 26 '13 12:03

Sowmya


People also ask

How do I change the input field to read only?

The readonly attribute is a boolean attribute. When present, it specifies that an input field is read-only. A read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it).

How do you make a toggle button readonly in HTML?

You can use the change event to restore the readonly status of the field. Then, when the div is clicked, remove the readonly attribute using date. removeAttribute('readonly') as Nidhin shows.

How can input field readonly in JQuery?

Projects In JavaScript & JQuery To make a textarea and input type read only, use the attr() method .

How do you add a readonly attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value. If the specified attribute already present, then the value is being set or changed.


1 Answers

Gets all elements with the name Edit and attaches a click handler. The variable prev is the previous input element and ro is that elements readonly attribute state (true / false).

Then we're setting the readonly state to ! ro (not ro), which just means "set it to the opposite of what it currently is (a toggle function if you will)", and focusing the prev input.

The last line targets the currently clicked button with this, and changes it's text with a ternary operator based on the state of the ro variable.

$('[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

like image 147
adeneo Avatar answered Sep 20 '22 11:09

adeneo