简体   繁体   中英

How to check if checkbox is checked inside a particular form?

I created a jQuery function to check if a checkbox is checked like so:

if ($('input:checkbox:checked').length > 0){ }

I have two set of check boxes in two separate forms. When I use above code it checks for checkboxes in both forms. I want the if condition only for one form. How can I achieve it?

You can include your form in selector by using its id or class etc,

By using form id

if ($('#yourFormId input:checkbox:checked').length > 0){ }

By using form class

if ($('.yourFormClass input:checkbox:checked').length > 0){ }

By using the index of form, eq(0) gives you first form and eq(1) second so on...

if ($('form:eq(0) input:checkbox:checked').length > 0) { }

You can use :eq() selector. Try the following:

if ($('form:eq(0) input[type="checkbox"]:checked').length > 0) { } // first form checkboxes
if ($('form:eq(1) input[type="checkbox"]:checked').length > 0) { } // second form checkboxes

please note that :checkbox selector is deprecated you can use input[type="checkbox"] instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM