拒绝更改复选框的状态

时间:2014-11-22 17:17:57

标签: javascript jquery 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>
&#13;
&#13;
&#13;

此代码有效。但是有更好的解决方案吗?

3 个答案:

答案 0 :(得分:3)

只需使用HTML的disabled属性:

&#13;
&#13;
<input type="checkbox" disabled />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如何简单地禁用你不会改变的那些:

document.getElementById("your_field_id").disabled = true;

答案 2 :(得分:0)

现在,我只看到一个解决方案:将元素和默认值传递给函数

&#13;
&#13;
window.doNotChange=function(el,v){
	$(el).prop({checked:v});
	alert('Can\'t touch this');
};
&#13;
<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>
&#13;
&#13;
&#13;

感谢您的回答