Reputation: 3315
I have a checkbox that calls a javascript function. When this checkbox is checked, other values in a form are auto filled out. The type of these other values are another checkbox and an option select field. I have the following in html:
<div id="NA" >
<input type="checkbox" name="remove_cd" value="r_on" id="r_on_cd" />N/A:
<select name="reason" id="reason_list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<font color="#cc0000">Reason Required</font><hr/></div>
In javascript, I have the following in a function:
...
var y = document.getElementById("NA").children;
for(var i=0; i<y.length; y++){
y[i].checked=true;
y[i].options.selectedIndex=2;
}
...
I'm a little confused as to why this isn't working. When I click on a checkbox in the form, the checkbox under the <div id="NA">
gets checked, but the option in the dropdown doesn't get changed. Ideas?
Upvotes: 1
Views: 912
Reputation: 13529
I'm not sure what exactly you want to do, but try this:
<div id="NA" >
<input type="checkbox" name="remove_cd" value="r_on" id="r_on_cd" />N/A:
<select name="reason" id="reason_list">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<font color="#cc0000">Reason Required</font><hr/></div>
<script>
window.onload = function() {
var y = document.getElementById("NA").children; // it's not a good idea to use children array, because if you add a new element in the begining your script will fail
var checkbox = y[0]; // it is better here to use: document.getElementById('r_on_cd');
var select = y[1]; // it is better here to use: document.getElementById('reason_list');
checkbox.onclick = function() {
select.options.selectedIndex = 2;
};
}
</script>
Upvotes: 0
Reputation: 26386
You have y++
instead of i++
in your loop. Try this
for(var i=0; i<y.length; i++){
y[i].checked=true;
y[i].selectedIndex=2;
}
calling .selectedIndex
on options
throws Cannot set property 'selectedIndex' of undefined
Upvotes: 2
Reputation: 50787
y[i].options.selectedIndex=2;
should probably just read:
y[i].selectedIndex=2;
Upvotes: 0