Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find checkboxes by value with javascript

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?

like image 296
MTplus Avatar asked Jun 05 '13 10:06

MTplus


People also ask

How do I check a checkbox in JavaScript?

In JavaScript, we can access the checkbox element using id, class, or tag name and apply '. checked' to the element, which returns either true or false based on the checkbox is checked.

How do you find checkbox is checked or not in JavaScript?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

What is the value of checkbox in JavaScript?

If a checkbox is marked or checked, it indicates to true; this means that the user has selected the value. If a checkbox is unmarked or not checked, it indicated to false; this means that the user has not selected the value.


2 Answers

Try querySelectorAll :

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

No need in jQuery , pure Vanilla JavaScript!

like image 182
Ivan Chernykh Avatar answered Oct 03 '22 16:10

Ivan Chernykh


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)

like image 20
Rob Avatar answered Oct 03 '22 16:10

Rob