Search code examples
javascriptpythondjangodjango-forms

Django How to get value of CheckboxSelectMultiple in Javascript in Template


I have a CheckboxSelectMultiple in a Django form like this :

forms.py

LIST= [
  ('Oranges', 'Oranges'),
  ('Cantaloupes', 'Cantaloupes')
]

testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple(choices=LIST)`)

I would like to get the Checkboxes value, each time that one of them is there is selected / unselected to populate another field of the form (email).

This is what I got so far but I can't retrieve the chekboxes value :

template.py

<script>
  $(function(){
    $('#id_testrever').change(function(){
      var a = $("#id_email").val();
      
      if ($("#id_testrever").val() == "Oranges")
        $("input[name=email]").val(a + "Oranges")
        
      if ($("#id_testrever").val() == "Mangoes")
        $("input[name=email]").val(a + " Mangoes")
    });
  });
</script>

Solution

  • If you're using MultipleChoiceField then your each checkbox will have an ID with a suffix, which contains the index of each checkbox. So to get the values of selected checkboxes, you've got to get all selected checkboxes and you can access ids like this:

    $('#id_testrever_0').val() // value of first checkbox
    $('#id_testrever_1').val() // value of second checkbox
    

    Or if you want to select all the checkboxes and get values of those intead of selecting one at a time you can do like this

    let selectedValues = [];
    $("input:checkbox[name=testrever]").on("change", function() {
      $("input:checkbox[name=testrever]:checked").each(function(){
        selectedValues.push($(this).val());
      });
      console.log(selectedValues);
    });
    

    In above code you can access values in selectedValues array.

    Your final code will look like this

    $("input:checkbox[name=testrever]").on("change", function() {
    
      var a = $("#id_email").val();
    
      $("input:checkbox[name=testrever]:checked").each(function(){
    
        let testrever = $(this).val();
    
        if (testrever == "Oranges")
          $("input[name=email]").val(a + "Oranges")
    
        if (testrever == "Mangoes")
          $("input[name=email]").val(a + " Mangoes")
    
      });
    });