最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

checkbox - Find checkboxes by value with javascript - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question edited Jun 25, 2014 at 20:48 Sam 7,39816 gold badges47 silver badges68 bronze badges asked Jun 5, 2013 at 10:19 MTplusMTplus 2,3915 gold badges38 silver badges63 bronze badges 2
  • You can iterate over all checkboxes and compare their value. There is no dedicated function to find form elements by value. – Felix Kling Commented Jun 5, 2013 at 10:22
  • @Magnus. Change the attribute value of name 3 to value = "chk3" and name = 4 value = "chk4". Same values are given. – UdayKiran Pulipati Commented Jun 5, 2013 at 10:24
Add a comment  | 

2 Answers 2

Reset to default 15

Try querySelectorAll :

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

No need in jQuery , pure Vanilla JavaScript!

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)

发布评论

评论列表(0)

  1. 暂无评论