Find checkboxes by value with javascript

夙愿已清 提交于 2019-12-13 14:26:28

问题


I have used this JavaScript to find the checkboxes I need and check them.

<script type="text/javascript">
function checkAll(c) {
    var chks = document.getElementsByName(c.name);
    for (var i = 0; i < chks.length; i++) {
        chks[i].checked = c.checked;
    }
}

But I cannot use that anymore and wonder if I could find them by their value names, lets say I have 3 checkboxes that are rendered like this..

<input name="2" type="checkbox" value="chk2" onclick="checkAll(this)">
<input name="3" type="checkbox" value="chk2" onclick="checkAll(this)">
<input name="4" type="checkbox" value="chk3" onclick="checkAll(this)">

If I then check one of the checkboxes with value="chk2" both of them should be checked, but no the one that have a value equals to chk3. Is this possible?


回答1:


Try querySelectorAll :

var chks = document.querySelectorAll("input[type='checkbox'][value='chk2']");

No need in jQuery , pure Vanilla JavaScript!




回答2:


Please consider using jQuery and a statement like this which checks all checkboxes with the value "chk2":

$("input:checkbox[value='chk2']").attr("checked", true);

Edit: A more elegant way would be the use of a ViewModel. Then you can bind the checkboxes to one single data entity and the checkboxes get checked/unchecked whenever the value of he underlying data changes. You can achieve that with knockout.js and it's easy to implement (http://knockoutjs.com)



来源:https://stackoverflow.com/questions/16937350/find-checkboxes-by-value-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!