skip to Main Content

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>

2

Answers


  1. 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")
    
      });
    });
    
    Login or Signup to reply.
  2. You can make a selector that selects the checkboxes under the type, so:

    $('#id_testrever input:checkbox')

    this will return all checkboxes. You can obtain all checked ones with:

    $('#id_testrever input:checkbox:checked')

    so you can for example obtain a list of the values of the checked checkboxes with:

    $('#id_testrever input:checkbox:checked').map(function() {
        return this.value;
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search