anderish
anderish

Reputation: 1759

Receiving Checkbox Values Using Ajax

I have the following checkbox definitions:

{% for member in team_profile %}
    <div class="checkbox">
        <label> <input type="checkbox" id="checkboxes" value="{{ member.user_id }}">{{ member.first_name }}</label>
    </div>
{% endfor %}

Where team_profile just contains a bunch of member names. So the I would like to get the value={{member.userid}} stuff.

So for my jquery i have:

var myCheckboxes = new Array();
$("input:checked").each(function() {
    data['myCheckboxes[]'].push($(this).val());
});

$.ajax({
    type:'POST',
    url:'createEvent/',
    data:{
        name: name,
        myCheckboxes: myCheckboxes,
    }
});

So I want to collect all the values and store them in an array called myCheckboxes. But I am getting an error data is not defined. Is there any other way to do this?

Thanks, Andy

EDIT:

Okay, I made the following changes:

var myCheckboxes = new Array();
$("input:checked").each(function() {
    data['myCheckboxes[]'].push($(this).val());
});

$.ajax({
    type:'POST',
    url:'createEvent/',
    data:{
        name: name,
        myCheckboxes: myCheckboxes,
    }
});

and in my views.py:

def createEvent(request):
    if request.method == "POST":
        member = request.POST.get('myCheckboxes')
        print(member)

But when I print out member, None gets outputted.

Upvotes: 2

Views: 1263

Answers (1)

dana
dana

Reputation: 18155

A couple suggestions...

For one, avoid using duplicate id="checkboxes" attributes, for example by using use name="checkboxes":

{% for member in team_profile %}
    <div class="checkbox">
        <label> <input type="checkbox" name="checkboxes" value="{{ member.user_id }}">{{ member.first_name }}</label>
    </div>
{% endfor %}

Also, the correct way to add data to an array is by using myCheckboxes.push(...):

var myCheckboxes = new Array();
$("input:checked").each(function() {
    myCheckboxes.push($(this).val()); // changed this line
});

$.ajax({
    type:'POST',
    url:'createEvent/',
    data:{
        name: name,
        myCheckboxes: myCheckboxes,
    }
});

Lastly, get the values on the server as follows:

def createEvent(request):
    if request.method == "POST":
        member = request.POST.getlist('myCheckboxes[]')
        print(member)

Upvotes: 1

Related Questions