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>
document.getElementsByName
to get element byname
attribute + you want to get the checked checkboxes? so you should check thechecked
attribute too, see my answer :) – user1823761 Jun 20 at 12:07