To find no of checkboxes in html using jQuery or javascript
Using the above code I have written following code
var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements; var cbs = []; //will contain all checkboxes var checked = []; //will contain all checked checkboxes for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == "checkbox") { cbs.push(inputs[i]); if (inputs[i].checked) { checked.push(inputs[i]); } } } var nbCbs = cbs.length; //number of checkboxes var nbChecked = checked.length; //number of checked checkboxesThe following code gives no of check boxes present and no of checked.
Using the above code I have written following code
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> function chking() { /* For Running jQuery */ var cbs = $("input:checkbox"); //find all checkboxes var nbCbs = cbs.size(); //the number of checkboxes var checked = $("input[@type=checkbox]:checked"); //find all checked checkboxes + radio buttons var nbChecked = checked.size(); /* For Running jQuery */ /* For Running Javascript */ var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements; var cbs = []; //will contain all checkboxes var checked = []; //will contain all checked checkboxes for (var i = 0; i < inputs.length; i++) { if (inputs[i].type == "checkbox") { cbs.push(inputs[i]); if (inputs[i].checked) { checked.push(inputs[i]); } } } var nbCbs = cbs.length; //number of checkboxes var nbChecked = checked.length; //number of checked checkboxes alert(nbCbs); alert(nbChecked); /* For Running Javascript */ } </script> </head> <body> <form method="post" action=""> <input type="checkbox" name="cricket" value="cricket" /> cricket<input type="checkbox" name="football" value="football" /> football<input type="checkbox" name="hockey" value="hockey" /> hockey<input type="checkbox" name="chess" value="chess" /> chess<input type="checkbox" name="cards" value="cards" /> cards<input type="button" value="check" onclick="chking();" /> </form> </body> </html>
No comments:
Post a Comment