HTML control array in JavaScript - checkbox array of 1 returns zero length

I use a checkbox of checkboxes to capture multiple selections

The following code with two flags works well and returns 2 as expected (or, however much).

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

I tried this in Internet Explorer and Chrome with the same results. While working, I have to turn on the hidden fake flag in the array to make sure that there are always two or more elements during code execution.

<!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> 
+4
source share
3 answers

JsFiddle working 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); } 
+5
source

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

+1
source

You can do this with jQuery:

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

Source: https://habr.com/ru/post/1487282/


All Articles