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
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: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
In above code you can access values in
selectedValues
array.Your final code will look like this
You can make a selector that selects the
checkboxes
under the type, so:this will return all checkboxes. You can obtain all checked ones with:
so you can for example obtain a list of the values of the checked checkboxes with: