mk8efz
mk8efz

Reputation: 1424

Django - Retrieve Values of Checkboxes

How do I retrieve the values of multiple html checkboxes and send it back to my view? The checkboxes have the same name:

<input type="checkbox" value="document_1" name="checkbox_1">
<input type="checkbox" value="document_2" name="checkbox_1">
<input type="checkbox" value="document_3" name="checkbox_1">

I'm trying to give the user the option the select multiple checkboxes and then send that data back to a Django view.

My hope is to send the data back to a Django view as a list of all the selected values with Ajax, although I'm just working out a regular form right now.

So If I selected the first and last checkbox, I would send this back to the view:

data = ["document_1", "document_3]

I have tried setting a variable like this:

var data = $('.checkbox_1:checked').val()

and I'm still working on the Ajax but haven't been able to make much progress.

Upvotes: 5

Views: 3778

Answers (3)

Pulkit Pahwa
Pulkit Pahwa

Reputation: 1422

<form action="">
    <input type="checkbox" name="checkbox_1" value="checkbox_1" class="checkbox">
    <input type="checkbox" name="checkbox_1" value="checkbox_2" class="checkbox">
    <input type="checkbox" name="checkbox_1" value="checkbox_3" class="checkbox">
    <input type="checkbox" name="checkbox_1" value="checkbox_4" class="checkbox">
    <button type="button" id="submit-button">Send data to server</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var selected_items = [];
    $(".checkbox").click(function(){
        var selected_item = $(this).val();
        var index = selected_items.indexOf(selected_item);
        if(index == -1)
        {
           selected_items.push(selected_item);
        }
        else{
           selected_items.splice(index, 1);
        }
    });
    $("#submit-button").click(function(){
        $.ajax({
            url: '/path/to/',
            data: {'checkboxes': selected_items.join(","), 'csrfmiddlewaretoken': {{csrfmiddlewaretoken}} },
            dataType: 'json',
            type: 'post',
            success: function (data) {
            }
        });
    });
})
</script>

In django views, you can get the value of checkboxes using request.POST['checkboxes']. Applying split(',') method to this value will separate values of every checkbox.

Upvotes: 0

arstj
arstj

Reputation: 88

Try to surround it with a form:

<form method="post" id="list-action">
<input type="checkbox" value="document_1" name="checkbox_1">
<input type="checkbox" value="document_2" name="checkbox_1">
<input type="checkbox" value="document_3" name="checkbox_1">
<button type="button" class="js-use-selected">Submit</button>
</form>

and then in your ajax, do this:

$(".js-use-selected").click(function () {
  $.ajax({
    url: '/path/to/',
    data: $("#list-action").serialize(),
    dataType: 'json',
    type: 'post',
    success: function (data) {

    }
  });
});

In your views.py you can get a list of the "checkbox_1" values by the name of checkbox elements:

values = request.POST.getlist('checkbox_1')

if it doesn't work, try this:

values = request.POST.getlist('checkbox_1[]')

And then, for example:

MyModel.objects.filter(fieldname__in=values)

Upvotes: 0

Rounin
Rounin

Reputation: 29521

You can:

  1. Test the boolean checked property for each checkbox (in either jQuery or in native javascript);
  2. Build an array from the results;
  3. Optionally convert the array into a conventional object (javascript arrays are already objects); and then
  4. Convert either the conventional object or the array into JSON (which you can then send via Ajax).

$(document).ready(function(){

    var checkedCheckboxes = [];

    $('button').click(function(){
        $('input').each(function(){
            if ($(this).is(':checked')) {
                checkedCheckboxes.push($(this).val())  
            }
        });

    // Now we have an array
    console.log('JS Array: ');
    console.log(checkedCheckboxes);

    // Convert array to standard Javascript Object Literal
    var checkedCheckboxesObject = $.extend({}, checkedCheckboxes);
    console.log('JS Object: ');
    console.log(checkedCheckboxesObject);

    // Convert Object Literal to JSON
    var checkedCheckboxesJSON = JSON.stringify(checkedCheckboxesObject);
    console.log('JSON: ');
    console.log(checkedCheckboxesJSON);

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
<input type="checkbox" value="document_1" name="checkbox_1">
<input type="checkbox" value="document_2" name="checkbox_1">
<input type="checkbox" value="document_3" name="checkbox_1">
<button type="button">Submit</button>
</form>

Upvotes: 2

Related Questions