I am trying to make a javascript function (although jquery is perfectly OK) that will return a number that corresponds to the number of checkboxes checked in a form. Seems simple enough but I can't figure out a good way of doing it.
Thanks.
Quickest and simplest method is to find a list of the checkbox elements by the className you've provided. List<WebElement> boxes = driver. findElements(By. className("checkbox")); int numberOfBoxes = boxes.
Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').
Try this:
var formobj = document.forms[0];
var counter = 0;
for (var j = 0; j < formobj.elements.length; j++)
{
if (formobj.elements[j].type == "checkbox")
{
if (formobj.elements[j].checked)
{
counter++;
}
}
}
alert('Total Checked = ' + counter);
.
With JQuery:
alert($('form input[type=checkbox]:checked').size());
$('form :checkbox:checked').length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With