英文:
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):
$('#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 minimize the code length and avoid the repetitions, maybe by using:
$("input:checkbox[name=testrever]").on("change", function() {
$("input:checkbox[name=testrever]:checked").each(function() {
// Your code here
});
});
if it's possible.
英文:
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) :
$('#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.
答案1
得分: 1
我不完全确定我是否完全理解你想要的内容。但如果你想要将 #id_email
的值与选中的复选框的值追加在一起,你可以使用以下代码:
$('$id_testrever input:checkbox').on('change', function() {
if(this.checked) {
const element = $('$id_email');
element.val(element.val() + this.value);
}
});
英文:
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);
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论