0

I need to deny to change the state of any checkbox:

window.doNotChange = function(event) {
  e = event || window.event;
  if (e) {
    e.stopPropagation();
    e.preventDefault();
    var t = $(e.target);
    t.prop({checked: typeof t.attr('checked') != 'undefined'});
  }
  alert('Deny to change THIS checkbox!');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" checked onchange="doNotChange(event)"> name 1 (readonly)</label></p>
<p><label><input type="checkbox" onchange="doNotChange(event)"> name 2 (readonly)</label></p>
<p><label><input type="checkbox" checked> name 3 (editable)</label></p>
<p><label><input type="checkbox" checked onchange="doNotChange(event)"> name 4 (readonly)</label></p>
<p><label><input type="checkbox"> name 5 (editable)</label></p>
<p>etc.</p>

This code works. But is there a better solution?

3 Answers3

3

Just use HTML's disabled attribute:

<input type="checkbox" disabled />
David Thomas
  • 249,100
  • 51
  • 377
  • 410
0

How about just simple disable the ones you don't wan't changes on:

document.getElementById("your_field_id").disabled = true;
olegaarde
  • 31
  • 3
0

Now, I see only one solution: to transfer the element and the default value to the function

window.doNotChange=function(el,v){
 $(el).prop({checked:v});
 alert('Can\'t touch this');
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><label><input type="checkbox" checked onchange="doNotChange(this,1)"> name 1 (readonly)</label></p>
<p><label><input type="checkbox" onchange="doNotChange(this,0)"> name 2 (readonly)</label></p>
<p><label><input type="checkbox" checked> name 3 (editable)</label></p>
<p><label><input type="checkbox" checked onchange="doNotChange(this,1)"> name 4 (readonly)</label></p>
<p><label><input type="checkbox"> name 5 (editable)</label></p>

Thanks for answers