I have an array with values which represent checkboxes on my website. I want to make the label of the correspinding checkbox become blue if the checkbox is clicked.
I have a working click function and it works perfectly, but only if I use the checkbox name directly (here is the checkboxname haustiere_erlaubt
:
$('#haustiere_erlaubt').click(function(){
if(document.getElementById("haustiere_erlaubt").checked) {
$("label[for=haustiere_erlaubt]").css("color", "#0d9eff");
} else {
$("label[for=haustiere_erlaubt]").css("color", "#b4b4b4");
}
});
I have multiple checkboxes on my website and its more efficient to use an array, because I dont want to write down the same code multiple times. But somehow it does not work eventhough the consol.log shows me the correct checkbox names:
var bool_checkboxes = ["haustiere_erlaubt", "bettwaesche_wird_gestellt", "grill_vorhanden", "safe_vorhanden", "kuehlschrank_vorhanden", "rauchen_erlaubt", "parkplatz_vorhanden",
"kochmoeglichkeit_vorhanden", "restaurant_im_haus_vorhanden", "handtuecher_werden_gestellt", "tv_vorhanden", "waschmoeglichkeit_vorhanden", "wlan_vorhanden"];
for (var bool_field = 0; bool_field < bool_checkboxes.length; bool_field++) {
console.log(bool_checkboxes[bool_field]);
$('#' + bool_checkboxes[bool_field]).click(function(){
if(document.getElementById(bool_checkboxes[bool_field]).checked) {
$("label[for=" + bool_checkboxes[bool_field] + "]").css("color", "#0d9eff");
} else {
$("label[for=" + bool_checkboxes[bool_field] + "]").css("color", "#b4b4b4");
}
});
}
I get this error message in the console.log when clicking on a checkbox:
Uncaught TypeError: Cannot read property 'checked' of null
at HTMLInputElement.<anonymous> (main.js:292)
at HTMLInputElement.dispatch (jquery.min.js:3)
at HTMLInputElement.r.handle (jquery.min.js:3)