DanielleC
DanielleC

Reputation: 127

Django: How to retrieve serialized checkbox values from ajax call in django views?

For example in html, I have a form that contains check-boxes :

<label>
    <input type="checkbox" name="check" value="check1">Option A
</label>
<label>
    <input type="checkbox" name="check" value="check2">Option B
</label>

And an AJAX call like this:

 $.ajax({
    data: $(#form).serialize(),
    type: $(#form).attr('method'),
    url: $(#form).attr('action'),
    datatype:'html',
    success: function() { 
        ...
    }
});

Since serialze() gives values like check=check1&check=check2 , the value of check only contains check2, the later assignment. Is there a way to get all checked values in an array?

Thanks in advance!

Upvotes: 1

Views: 1188

Answers (1)

Rieljun Liguid
Rieljun Liguid

Reputation: 1531

I would like to comment but my reputation is not enough so I'll just post an answer. If you want to just get all the values of 'check' then you can use getlist in the view. Something like this:

# Sample URL
# sample.com/?check=check1&check=check2

# In the view you can do it like this
values = request.GET.getlist('check')

# values will be equal to [u'check1', u'check2']

This maybe similar to you problem Jquery and Django multiple checkbox

Upvotes: 3

Related Questions