Ok so I have a code that would show different forms based on dropdown selection
Here's the fiddle to that..
Well its always giving me Test1 which means its not changing the div display, it's working on JSFiddle but not on the webpage.. and here's my webpage markup
<html>
<body>
<style>
.hidden {
display: none;
}
</style>
<script type='text/javascript'>
document.getElementById('options').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
</script>
<select name="options" id="options">
<option value="1"> Display </option>
<option value="2">Wka</option>
</select>
<div id="1" class="hidden" style="display: block">Test 1</div>
<div id="2" class="hidden">Test 2</div>
</body>
</html>
The best thing to do when such problem comes
works in jsfiddle and not on webpage
is to see the source of the fiddle page.Your source of the fiddle appears as:
Paste the above code directly and it will work.
After pasting the code directly then you can remove unncecessary lines like below from the fiddle:
You seem to be missing
<head>
tags.You need a onload function so your code is run after your HTML is loaded. Try this:
You can also add the code after all your HTML, before the end of the body tag.
And note that in your post you are missing
<head>
tags.The page is loaded into the DOM from the top down.
Your
document.getElementById('options').onchange
is being called before the element with idoptions
exists in the DOM.If you put your script below the divs, it'll work because the divs are now there before the script is called.
That is because in the fiddle your code is set to run at
onLoad
, but in your code its running before the DOM is created.Wrap your code into a
window.onload
event like this:Anyway, like @positivew remembered, your code misses the
<head>
tag. Is semantically correct to put your JS scripts inside it.Jsfiddle is running your script
.onload
of thewindow
object, without you realizing it. This allows your script to pause on execution until the DOM is ready to be manipulated.To have it work in your own environment, you can:
<body>
)Leave your code above the
<body>
and run it onload of the window object, e.g.