0

I understood that adding readonly attribute to check box does not make it readonly. Also adding disable attribute will not post the value.

On this SO post there are different options suggested to make the check box readonly.

However, i want to toggle the readonly state of the check box on some button click, and also post the value on form submit.

So as suggested i added "return false" on click event. Works fine. However how do i toggle this behavior?

<button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" onClick="return false;" name="CheckBox1" />


$(document).ready(function() {

   $("#btn").click(function()
   {
      //how do i toggle readonly here
   })

});
LP13
  • 30,567
  • 53
  • 217
  • 400

1 Answers1

1

One way to do it is to toggle a classname on the checkbox, then test for the presence of that classname when the user tries to change the checkbox state.

(You could use a data attribute instead, but this way has the added benefit of letting you give the user some visual cue that the input is readonly.)

$("#btn").on("click", function() {
  $('input[name="CheckBox1"]').toggleClass("readonly");
});

$('input[name="CheckBox1"]').on("click", function() {
  if ($(this).hasClass('readonly')) {return false}
});
.readonly {
  opacity: 0.5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="btn">Toggle</button>
<input type="checkbox" value="false" name="CheckBox1" />
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53