Forum Moderators: open
I can't seem to figure out how to get the onchange event working from the script itself.
<html>
<head>
<title>Swap HTML</title>
<script>
function swap() {
var countryValue = document.getElementById('cntry').value;
var stateDiv = document.getElementById('stateField');
if (countryValue == 'United States') {
stateDiv.innerHTML='<label for="state">state/county:</label> <select name="state" id="state"><option value="AA">Select a state...</option><option value="NY">New York</option><option value=AZ>Arizona</option></select>';
} else if (countryValue == 'United Kingdom') {
stateDiv.innerHTML='<label for="state">state/county:</label> <input type="text" name="state">';
}
}
</script>
</head><body>
<form name="test1">
<div id="stateField"><label for="state">state/county:</label> <input type="text" name="state"></div>
<div id="cntryField"><label for="cntry">country:</label> <select name="cntry" id="cntry" onchange="swap();"><option value="BB">Select a country...</option><option value="United States">United States</option><option value="United Kingdom">United Kingdom</option></select></div>
<input type="button" name="submit" value="submit">
</form>
</body>
</html>
So in short I need to remove the onchange event from the select tag and somehow make it actionable in the script tag.
I tried adding this function and using onload event on the body tag but it didn't work though firebug gave me back no errors...
function loadSwap() {
if (document.getElementById('cntry').onchange) {
swap();
}
}
after the form i've added...
<script>document.test1.cntry.onchange = swap</script>
this now handles my form as i need.
here is the new code that works:
<html>
<head>
<title>Swap HTML</title>
<script>
function swap() {
var countryValue = document.getElementById('cntry').value;
var stateDiv = document.getElementById('stateField');
if (countryValue == 'United States') {
stateDiv.innerHTML='<label for="state">state/county:</label> <select name="state" id="state"><option value="AA">Select a state...</option><option value="NY">New York</option><option value=AZ>Arizona</option></select>';
} else if (countryValue == 'United Kingdom') {
stateDiv.innerHTML='<label for="state">state/county:</label> <input type="text" name="state">';
}
}
</script>
</head><body>
<form name="test1">
<div id="stateField"><label for="state">state/county:</label> <input type="text" name="state"></div>
<div id="cntryField"><label for="cntry">country:</label> <select name="cntry" id="cntry" onchange="swap();"><option value="BB">Select a country...</option><option value="United States">United States</option><option value="United Kingdom">United Kingdom</option></select></div>
<input type="button" name="submit" value="submit">
</form><script>document.test1.cntry.onchange = swap</script>
</body>
</html>