dnsko dnsko - 6 months ago 24
jQuery Question

Changing multiple elements with same id

I'm not familiar with JQuery at all, but I was wondering if it's possible to change all elements with the same id on actions.

$(document).ready(function() {
document.getElementById("id_scheduled_time").disabled = true;
document.getElementById("id_scheduled_day").disabled = true;
});

$('#id_schedule_type').on('change', function() {
if ($("#id_schedule_type").prop('selectedIndex') == 0) {
document.getElementById("id_scheduled_time").disabled = true;
document.getElementById("id_scheduled_day").disabled = true;

}
else {
document.getElementById("id_scheduled_time").disabled = false;
document.getElementById("id_scheduled_day").disabled = false;
};
});


$('#id_scheduled_period').on('change', function() {
if ($("#id_scheduled_period").prop('selectedIndex') == 2) {
$('#id_scheduled_minute').attr("placeholder","Insert number 1-15").val("");
} else {
$('#id_scheduled_minute').attr("placeholder","Insert number 1-45").val("");
};
});


Yes, this code looks like shit but does it work for now. The problem for me is that there are multiple tabs with selection boxes and input fields which all have the same id (for example
id_scheduled_time
)

Now what it does it that it works fine in one single tab, but does nothing for the other id's.
The question here is: how do I change all the elements the same way for the selection indices

Answer

Instead of selecting the element with $('#my-id'), you could use $('[id="my-id"]') to select all of them.

However, as all the comments mention you should really switch to classes. ID's are not meant to be used more than once on a page.