samedi 20 mai 2023

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.




Aucun commentaire:

Enregistrer un commentaire