[Answer]-Validate at least One check box is checked in django html template via Ajax

1๐Ÿ‘

โœ…

$("#delete").click(function() {
    if ($('input[type="checkbox"]:checked').length > 0) {
        alert("Checked");
    } else {
        alert("Not checked");
    }
});

If you have other checkboxes on page then add a class to your <input> and select items in JS by this class:

<input type="checkbox" class="deletechk" name="selectedvalues[]"
                                         value="{{ result.object.user_id }}">

And in Javascript code:

if ($('.deletechk:checked').length > 0) {
    ...
}
๐Ÿ‘คcatavaran

0๐Ÿ‘

You need to change your Javascript to below and instead of alerts can set a flag and break loop by returning false if they have checked a checkbox (see this Fiddle):

$("#delete").click(function(){
    var checkboxes = $('input[type="checkbox"]');
    $(checkboxes).each(function(index) {
        if($(this).is(':checked')) {
            alert('checked');
        } else {            
            alert('You must select at lease one user');
        }      
    });
});
๐Ÿ‘คZaki

0๐Ÿ‘

In HTML add :

<input type="checkbox" id="{{result.object.user_id}}"       
name="selectedvalues[]" value="{{ result.object.user_id }} class="mybox">

jquery:

$( "#delete" ).click(function(e) {
var checks=( $(".mybox").val());
if(!checks)
{
  alert('You must select at lease one user');
  e.PreventDefault()
{



});
๐Ÿ‘คblaz1988

Leave a comment