javascript - How to validate that at least 1 checkbox per group was checked in a form? -


i building page user able choose various goods category ( e milk/fruit...) done in form.

then, send them server , processing.

<div>     <div><input type="checkbox" name="milk" value="yogurt1"/>yogurt1</div>     <div><input type="checkbox" name="milk" value="yogurt2"/>yogurt2</div>     <div><input type="checkbox" name="milk" value="yogurt3"/>yogurt3</div> </div>                <div>     <div><input type="checkbox" name="fruit" value="apple"/>apple</div>     <div><input type="checkbox" name="fruit" value="pear"/>pear</div>     <div><input type="checkbox" name="fruit" value="melon"/>melon</div> </div>    .... 

q: how can validate user has chosen @ least 1 product each category ( i.e. @ list 1 milk item , @ least 1 fruit item checked)?

you can use attribute selector :checked pseudo-selector follow:

if ($(':checkbox[name="milk"]:checked').length > 0) {     alert('min 1 checked'); } 

for multiple groups:

if ($(':checkbox[name="milk"]:checked').length == 0 || $(':checkbox[name="fruit"]:checked').length == 0 || ...) {     alert('please check @ least 1 checkbox group'); } 

demo


Comments

Popular posts from this blog

How to provide Authorization & Authentication using Asp.net, C#? -

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

How to use Authorization & Authentication in Asp.net, C#? -