onselect work from the second time only
I have below code working as desired but the on select works only from the second select change.
Any idea how to fix that?
working sample
<html>
<head>
<title>select & select</title>
<script type='text/javascript'>
var select2data = {
'English': [['One', 1], ['Two', 2], ['Three', 3]],
'Spanish': [['Uno', 1], ['Dos', 2], ['Tres', 3]]
};
function change_second_select(){
var sel1 = document.getElementById('select1')
, sel2 = document.getElementById('select2');
sel1.onchange = function() {
var os = 开发者_Go百科select2data[sel1.value]; // Get the options required by select1.
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try { // Add each option, allowing for browser differences.
sel2.add(o);
} catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
};
}
</script>
<select id="select1" onchange="change_second_select();">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="select2">
</select>
</head>
</html>
Change your change_on_select to as below:
Working example @ http://jsfiddle.net/3dCyw/1/
function change_second_select(){
var sel1 = document.getElementById('select1')
, sel2 = document.getElementById('select2');
var os = select2data[sel1.value]; // Get the options required by select1.
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try { // Add each option, allowing for browser differences.
sel2.add(o);
} catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
}
this works as well (jquery)
http://jsfiddle.net/RwxWx/
var select2data = {
'English': [['One', 1], ['Two', 2], ['Three', 3]],
'Spanish': [['Uno', 1], ['Dos', 2], ['Tres', 3]]
};
$(document).ready(function() {
$("#select1").bind("change", function() {
sel2 = $("#select2").get(0);
var os = select2data[this.value];
if (os) {
sel2.options.length = 0; // Clear the options for select2.
for (var i=0; i<os.length; i++) {
var o = new Option(os[i][0], os[i][1]);
try {
// Add each option, allowing for browser differences.
sel2.add(o);
}
catch (ex) {
sel2.add(o, null);
}
}
sel2.selectedIndex = 0;
}
return true;
});
});
</script>
<select id="select1">
<option value="English">English</option>
<option value="Spanish">Spanish</option>
</select>
<select id="select2">
Agree with Cybernate.
sel1.onchange = function() {...}
This means you attach the event to the element, but not excute it.
精彩评论