I’ve been trying to load up a DIV by default (dpara) and then allow the user to switch through DIVs depending on the button they press.
On page load – dpara is visible but dtab and ddl are not.
If the user picks dtab for example, dpara is hidden, dtab becomes visible and ddl remains hidden.
But this doesn’t seem to be working since I’ve updated my code from this:
<script type='text/javascript'>
function arrange(div_id) {
// First make all the divs hidden...
divs = document.getElementsByTagName('div');
for( var i = 0; i < divs.length; i++ ) {
divs[i].style.display = 'none';
}
// Now make the one we want to be visible visible...
document.getElementById(div_id).style.display = 'block';
}
</script>
<form>
<input type='button' value='dpara' onclick='arrange(this.value);' />
<input type='button' value='dtab' onclick='arrange(this.value);' />
<input type='button' value='ddl' onclick='arrange(this.value);' />
</form>
<div id='dpara'>
123
</div>
<div id='dtab'>
456
</div>
<div id='ddl'>
789
</div>
In addition to this var visibleDiv is mean to store the id of the div I’m passing through – but on alert it returns [object HTTPInputElement]. Is there a few steps I’ve missed? Here is mu new code below:
<script type='text/javascript'>
var visibleDiv;
function arrange(div) {
// Cache the passed in 'div' as the currently visible one
visibleDiv = div;
alert(visibleDiv);
// First make all the divs hidden...
var divs = document.getElementsByTagName('div'),
i,
len;
for (i = 0, len = divs.length; i < len; i++) {
divs[i].style.display = 'none';
}
// Now make the one we want to be visible visible...
visibleDiv.style.display = 'block';
}
</script>
<form>
<input type='button' value='dpara' onclick='arrange(this);' />
<input type='button' value='dtab' onclick='arrange(this);' />
<input type='button' value='ddl' onclick='arrange(this);' />
</form>
<div id='dpara'>123
</div>
<div id='dtab' style='display: none'>456
</div>
<div id='ddl' style='display: none'>789
</div>
Try this updated version:
JS Fiddle demo.
The problems were that you were passing the DOM node into the function, while you needed the
valuefrom that node. To get around this you could have used:onclick="arrange(this.value);"or, as I’ve chosen to do, pass the DOM node into the function, and then find the value within the function.Secondly you were assuming that the JavaScript would find the right
divelement without invoking thedocument.getElementById()method, which I’ve corrected, assigning the the DOM node returned bydocument.getElementById(div.value)to the variablevisibleDiv. I’ve also removed thealert(). But that wasn’t a problem, just to make it look a little better.