So I'm trying to write a simple show hide script that will upon checking a given radio button show the container that has the same id as the radio button that was checked, however this is where I'm stuck because the process only seems to work 1 way.
I can set the default state to make things hidden and I can make each of those hidden elements visible again upon clicking the corresponding radio button the problem is once there corresponding radio button is no longer checked those elements don’t switch back to the default state and thus remain visible and I don't understand why? because I had amused that the change event would work the same way as the :checked pseudo-class does in css
So all i would have to do is set the default state and then define when happens when one of the radio buttons is checked and then each time the script is fired the targeted element would be made viable and the previously targeted element would be made invisible again.
however the change event does seem to work this way and i cant figure out how to make all the containers except the one that is selected one invisible.
ok so here is a simplified version of the page I'm working on
Code: Select all
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
div.container
{
display:none
}
</style>
</head>
<body>
<main>
<div id="left">
<input type="radio" name="button" id="foo">
<label for="foo">foo</label>
<br><input type="radio" name="button" id="bar">
<label for="bar">bar</label>
<div id="right">
<div class="container" data-name='foo'>
<p>some content that should be hidden by default</p>
</div>
<div class="container" data-name='bar'>
<p>some content that should be hidden by default</p>
</div>
</div>
</main>
<script>
function checked(event)
{
var id = event.target.id;
var selected = document.querySelector('[data-name="'+ id +'"]');
selected.style.cssText="display:block";
}
var inputs = document.querySelectorAll("input");
for (i = 0; i < inputs.length; i++)
{
inputs[i].addEventListener("change", checked);
}
</script>
</body>
</html>
what should happen when i check the radio button with the id bar is that the box with the data-name="bar" should appear which it does however since the radio button with the id foo is no longer checked the box with the data-name="foo" should become invisible again which it doesn't and as i already mentioned I don't understand why because i though the change event was supposed to work like the :checked pseudo-class so when the radio button is no linger checked it should automatically switch back to the default state.
anyone have any idea what I'm missing ?