0

Could you help me how to validate different names of checkboxes at a time. It means i have a different levels of users. User select at least one Role. How to validate the checkboxes? Here my code like this

<input type="checkbox" name="is_admin" id="is_admin"/>
<input type="checkbox" name="is_marketing" id="is_marketing"/>
<input type="checkbox" name="is_school_admin" id="is_school_admin"/>
<input type="checkbox" name="is_trainer" id="is_trainer"/>
<input type="checkbox" name="is_coordinator" id="is_coordinator"/>

Like this my html Form is there. In this roles user select atleast one role. Please help me how to validate using java script or jquery. Thanks in advance

1
  • you can use :checkbox selector Commented Feb 19, 2014 at 12:30

2 Answers 2

2

Add a class to all checkboxes

<input type="checkbox" class="usertype" name="is_admin" id="is_admin"/>
<input type="checkbox" class="usertype" name="is_marketing" id="is_marketing"/>
<input type="checkbox" class="usertype" name="is_school_admin" id="is_school_admin"/>
<input type="checkbox" class="usertype" name="is_trainer" id="is_trainer"/>
<input type="checkbox" class="usertype" name="is_coordinator" id="is_coordinator"/>

then use class selector to select those checkboxes and use .is() and :checked-selector to check whether atleast one of them is checked

if(!$('input.usertype').is(':checked')){
    alert('select atleast one user type')
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here you can see it loop through all and display the value of checked in a separate output html element. http://jsfiddle.net/Np6aY/

HTML:

<input type="checkbox" name="is_admin" id="is_admin" />
<input type="checkbox" name="is_marketing" id="is_marketing" />
<input type="checkbox" name="is_school_admin" id="is_school_admin" />
<input type="checkbox" name="is_trainer" id="is_trainer" />
<input type="checkbox" name="is_coordinator" id="is_coordinator" />
<input type="button" id="getValButton" value="Get Values">
<div class="checkboxOutput"></div>

Javascript:

$('#getValButton').on('click', function () {
    var outputText = '';
    $('input[type=checkbox]').each(function (index, el) {
        outputText += $(el).attr('name') + ': ' + $(el).is(":checked") + '<br>';
    });
    $('.checkboxOutput').html(outputText);
});

1 Comment

After having seen @Arun P Johny's answer I think I may have misread the question. Keeping it here for you to decide!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.