Gman Gman - 1 year ago 83
Javascript Question

jQuery check if Checkboxes are on page

I have a form that loads via ajax. Depending on the parameters sent to fetch the form, the form may have no checkboxes or it may have one or more check boxes.

I want to check if a checkbox is present on the page and if yes prompt the user to select one during validation if not selected.

If present, the checkboxes have the same class and a different ID.

<input type="checkbox" name="associatedClass"
value="$associatedClsNumVal" class="getAssociatedClass"
id="$associatedClsNumVal" />

What is the best approach? Can jquery "sense" if there are checkboxes on a page/in a form?


Answer Source

The easiest way is to check if there are any inputs of the type checkbox on the page. With jQuery you can use CSS selectors such as input[type="checkbox"] to find elements in the DOM. Combine that with .length and you can get how many there are on the page. The complete jQuery code for this would be

if ( $('input[type="checkbox"]').length ) {
    // Validate checkboxes

If there could be other checkboxes on the page that you wouldn't want validated then you can limit your search to a particular element. For example, if you only wanted to validate checkboxes within a specific form with an ID of myForm then you can select the form and use .find() to search for checkboxes within and only within that form.

if ( $('#myForm').find('input[type="checkbox"]').length )
    // Validate checkboxes

However with the validation you probably want to check each input individually and so instead of just checking the length to make sure there is at least one checkbox on the page we can use .each to find all checkboxes and then process them one at a time.

$('input[type="checkbox"]').each(function () {
    // Validate this checkbox

The advantage of that is if there are none on the page it won't try and validate anything and it's perfectly valid, so we don't need to check to see if there are any before our validation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download