0

I have a input <input type="text" value="1" readonly id='aaa'/>.

I would like to give it a function when user check the box then can edit the value of id=aaa.

Sample:

<input type="text" value="1" readonly/> <input type="checkbox" /> Checked this if you want to edit the value.

Thank you.

1
  • Give appropriate Id to check box and use below code : if($("#CheckboxId").is(":checked")) { $("#aaa").removeAttr("readonly"); }else{ $("#aaa").attr("readonly","readonly"); } Commented Jun 18, 2019 at 8:28

2 Answers 2

1

Add an onchange event to the checkbox that changes to readOnly attribute of its previous sibling (the textfield)

<input type="text" value="1" readonly id="aaa" />
<input type="checkbox" onchange="getElementById('aaa').readOnly = !this.checked" />
Checked this if you want to edit the value.
Sign up to request clarification or add additional context in comments.

1 Comment

+1 b/c, as you have it, readOnly should be linked to this.checked, given the label text (instead of just toggling the readOnly state), which I've incorporated into my answer.
1

You want to use JavaScript to change the readOnly property. Set it to the opposite of whether the checkbox is checked.

document.getElementById('checksome').addEventListener('click', function() {

  var changeThis = document.getElementById('readsome');

  changeThis.readOnly = !this.checked;
});
<input id="readsome" type="text" value="1" readonly>
<label><input id="checksome" type="checkbox"> Click this to edit</label>

2 Comments

Is there a reason you have chosen the click event instead of the change event? I toggled the checkbox using the keyboard and to my surprise this also triggers the click event in Chrome.
@dehart In FF, too. (That's about everybody these days!) Not really; just because OP said click, and I know click is consistent, so I did the same. (Fuzzy memory of some problem with change event, but no idea where/when from.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.