Patrick
Patrick

Reputation: 43

HTML Control Array in JavaScript - Checkbox array of 1 returns zero length

I'm using a control array of checkboxes to capture a multiple selection

The following code, with two checkboxes, works well and returns a value of 2 as expected (or however many are there).

However if there is only one checkbox item in the array, it returns a length of 0 (zero).... why is this? Shouldn't it return a length of 1?

I have tried this in Internet Explorer and Chrome with the same results. As a work around I am having to include a hidden bogus checkbox in the array to make sure there is always two or more items when I run the code.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title></title>
    <script language="javascript" type="text/javascript">
        function categoryOnClick() {
            var selectedRows = document.searchForm.elements['categorySelect[]'];
            alert(selectedRows.length);
        }
    </script>
</head>
<body>
    <form name="searchForm" action="">
        <input type="checkbox" name="categorySelect[]" id="1" onclick="categoryOnClick();"/>
        <input type="checkbox" name="categorySelect[]" id="2" onclick="categoryOnClick();"/>
    </form>
</body>
</html>

Code that returns 0 (zero) length...

<form name="searchForm" action="">
     <input type="checkbox" name="categorySelect[]" id="1" onclick="categoryOnClick();"/>
</form>

Upvotes: 4

Views: 17930

Answers (3)

Rachit Doshi
Rachit Doshi

Reputation: 183

In javascript you can do

function categoryOnClick() {
    var count = document.querySelectorAll("input[type=checkbox]").length;
    var checkedElements = 0;
    for (var i = 0; i < count; i++) {
        checkedElements = checkedElements + parseInt((document.querySelectorAll("input[type=checkbox]")[i].checked) ? 1 : 0);    
    }
    alert(checkedElements);
}

and in jquery :

function categoryOnClick() {           
    alert($('input:checked').length)
}

Hope that helps

Upvotes: 1

derHofbauer
derHofbauer

Reputation: 61

You can do this using jQuery:

function categoryOnClickjQuery() {
    var selectedRows = $('form input').attr('name', 'categorySelect[]');
    alert(selectedRows.length);
}

Upvotes: 0

user1823761
user1823761

Reputation:

Working jsFiddle Demo

function categoryOnClick() {
    var rows = document.getElementsByName('categorySelect[]');
    var selectedRows = [];
    for (var i = 0, l = rows.length; i < l; i++) {
        if (rows[i].checked) {
            selectedRows.push(rows[i]);
        }
    }

    alert(selectedRows.length);
}

Upvotes: 5

Related Questions