Muhammad Taqi
Muhammad Taqi

Reputation: 5424

Validate at least One check box is checked in django html template via Ajax

I am showing pagination gird on django templates,

{% for result in page.object_list %}
<tr>
<td style="border:0;border-bottom:1px solid #eeeeee;">
<input type="checkbox" id="{{result.object.user_id}}" name="selectedvalues[]" value="{{ result.object.user_id }}">
            </td>
<td>.....</td>
<tr>
{% endfor %}

and there is a button at the end of this to delete the users. I want to validate that on delete button press it should validate that at least one user is selected via check box.

$("#delete").click(function(){
    var $checkboxes $('# td input[type="checkbox"]');
    $('.checkbox input').each(function(index) {
        if($(this).is(':checked')) {
            break;
        } else {
            $(this).attr('value', 'False');
        }
      alert('You must select at lease one user');
    });

    });

but it is not working.....

Upvotes: 0

Views: 1175

Answers (3)

blaz1988
blaz1988

Reputation: 366

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()
{



});

Upvotes: 0

Zaki
Zaki

Reputation: 5600

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');
        }      
    });
});

Upvotes: 0

catavaran
catavaran

Reputation: 45575

$("#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) {
    ...
}

Upvotes: 1

Related Questions