user10768139
user10768139

Reputation:

How to change read-only property of a form input with the click of button

I have created a form which has some Readonly input fields and an icon next to all of them. How do I change the Readonly property of the particular field when I click the icon next to it.

Form

<div class="input-group">
<input class="input--style-3" type="text" name="phone" id="phone" placeholder="Phone" value= "<?php echo $this->session->userdata('phone'); ?>" />
<span class="input-group-addon"><i class="glyphicon glyphicon-edit"></i></span>
</div>

Upvotes: 0

Views: 1102

Answers (1)

Rack Sinchez
Rack Sinchez

Reputation: 111

$('.input-group-addon').click(function(){
  $(this).parent() // gets parent container 'input-group'
    .children('input') // gets the input in the container
    .removeAttr('readonly'); // removes the readonly attr from the input
});
  • We're binding a function to the click of the element (in your case the icon)
  • We're selecting the parent of 'this' to get the element our icon is contained within
  • We're finding a child (an element directly inside our parent, adjacent to our icon) that is of type 'input' (there should only be one if you're marking up semantically)
  • We're removing an attribute from the input element

I tested this here with perfect result (before clicking the red square you cannot change the telephone number) https://codepen.io/anon/pen/pXXPNo

I hope that not only moves you forwards but aids in your understanding

Also, if you're creating elements on the fly instead of having them in the DOM come load, you'll need to change your binding like so:

$('body .input-group-addon').on("click", function(){
  $(this).parent() // gets parent container 'input-group'
    .children('input') // gets the input in the container
    .removeAttr('readonly'); // removes the readonly attr from the input
});

Upvotes: 2

Related Questions