javascriptdjangocheckboxmultiplechoicefield

Django get id of the selected checkbox on CheckboxSelectMultiple widget in Javascript


I have checkboxes in Django from a form :

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

I would like to return only the ID (and then the value) of the last selected checkbox on .change event only when it's checked (when it's unchecked I don't want anything to happen).

I managed to do so with the following (thanks to this answer) :

Django How to get value of CheckboxSelectMultiple in Javascript in Template

$('#id_testrever_0').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_0').is(':checked')) {
        testrever = $('#id_testrever_0').val();
        $("input[name=email]").val(a + testrever)
    }
})
    $('#id_testrever_1').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_1').is(':checked')) {
        testrever = $('#id_testrever_1').val();
        $("input[name=email]").val(a + testrever)
    }
})

But I would like to achieve it in a more elegant way to minimise the code lenght and avoid the repetitions.

maybe by using

$("input:checkbox[name=testrever]").on("change", function() 

  $("input:checkbox[name=testrever]:checked").each(function()

if it's possible.


Solution

  • I'm not entirely convinced I I fully understand what you want. But if you want to append the value of #id_email with the value of the checkbox checked, you can use:

    $('#id_testrever input:checkbox').on('change', function() {
        if(this.checked) {
            const element = $('#id_email');
            element.val(element.val() + this.value);
        }
    });