runnane Everything that matters ++

18Jul/080

Checking checkboxes, not always a breeze

So, I was sitting here and debugging some code for more than three hours. And finally, I figured it out: You cannot set a checkbox as checked until you have appended it to a container.

Code that does not work:

var newEl = document.createElement('input');
newEl.type = 'checkbox';
newEl.value = 'yes';
if(value == '1'){
   newEl.checked = "checked";
}
                               
$('AttributeValue_Container').appendChild(newEl);

Working code:

var newEl = document.createElement('input');
newEl.type = 'checkbox';
newEl.value = 'yes';

$('AttributeValue_Container').appendChild(newEl);
if(value == '1'){
  newEl.checked = "checked";
}

Really annoying 😉

Filed under: HTML/JS No Comments