When people selected the dropdown and then the checkbox will be auto checked if the selected value of dropdown is not empty. But I met “sel[i] is undefined” error.
Javascript part:
var chk = document.getElementsByTagName("input");
var sel = document.getElementsByTagName("select");
for (var i=0; i< sel.length; i++) {
sel[i].onchange = function(){
if (sel[i].value !== ''){
chk[i].checked = true;
}
else{
chk[i].checked = false;
}
};
}
HTML part:
<form name="form1">
<div class="container">
<input id='checkbox_id1' name='checkbox_id1' type='checkbox' value='1' /></label>
Select
<label>
<select id="select_id1" name="select">
<option value=""></option>
<option value="111">111</option>
<option value="222">222</option>
</select>
</label>
<hr>
<input id='checkbox_id2' name='checkbox_id1' type='checkbox' value='1' /></label>
Select
<label>
<select id="select_id2" name="select">
<option value=""></option>
<option value="111">111</option>
<option value="222">222</option>
</select>
</label>
</div>
jsfiddle: http://jsfiddle.net/planetoid/GwEuu/
Your value of
iis not what you think it is because theforloop has run to completion before any of the event handlers are actually called, thusiis the value at the end of theforloop.To capture the appropriate value of
ifor each event handler, you can use a self executing function like this that captures it in a closure for each specific event handler:Working demo: http://jsfiddle.net/jfriend00/yds6w/
FYI, I’ve also simplified the
.checkedassignment code.But, after looking at your code a bit, I believe this may be a better way of implementing it that doesn’t need the self executing function. Rather than rely on perfectly parallel arrays of checkboxes and input tags, this just converts the ID of the select to the ID of the corresponding checkbox and uses
thisto reference the select element. So,iis not used in the event handler.
Working demo: http://jsfiddle.net/jfriend00/g3UQG/