2

So, i'm making a site for a project. I have 2 radio buttons, if the radio button: 'Yes' is checked a div has to be shown on the same page at the moment when the radio button is checked. When the radio button 'no' is checked nothing has to happen and the div shouldn't be shown. here's the thing is was trying but it just won't work. I don't know what's wrong and can't find a solution on the web.

Here's my code:

<?php $ervaringja = 0; ?>

    Hebt u enige ervaring met Fitnessen? 
    <input type="radio" name="ErvaringJa_Nee"
    <?php if (isset($Ervaring) && $Ervaring=="Ja") $ervaringja = 1;?>
    value="Ja">Ja
    <input type="radio" name="ErvaringJa_Nee"
    <?php if (isset($Ervaring) && $Ervaring=="Nee") echo "checked";?>
    value="Nee">Nee<br>

    <?php 
    if ($ervaringja == 0){
        echo '<script>'. 'ervaringjanee()'. '</script>';
    }
    ?>

And the script:

<script>
    function ervaringjanee() 
        {
            document.getElementById("WelkeErvaring").style.display = "hidden";
        }
</script>

but the div keeps showing up, can some one help me?

1 Answer 1

6

To hide an element, it's not display: hidden;, it's display: none;.

Also, what you write in PHP is done ONLY when the page is loading. To make a page change with PHP, you have to make it reload. What you do in JavaScript can happen at any time. It usually reacts to events triggered by the user.

I would advise putting only JavaScript in charge of showing/hiding the div. Something like the code below:

Hebt u enige ervaring met Fitnessen?
<input type="radio" name="ErvaringJa_Nee" value="Ja"
    <?php if (isset($Ervaring) && $Ervaring == "Ja") {echo 'checked="checked"';} ?>
/>
<input type="radio" name="ErvaringJa_Nee" value="Nee"
    <?php if (!isset($Ervaring) || $Ervaring == "Nee") { echo 'checked="checked"';} ?>
/>
<div id="WelkeErvaring">
    ....
</div>

<script>
var div = document.getElementById("WelkeErvaring");
var ja = document.querySelector("input[name=ErvaringJa_Nee][value=Ja]");
var nee = document.querySelector("input[name=ErvaringJa_Nee][value=Nee]");
function toggleDiv() {
    if (ja.checked) {
        div.style.display = "block";
    } else {
        div.style.display = "none";
    }
};
toggleDiv();
ja.addEventListener("change", toggleDiv);
nee.addEventListener("change", toggleDiv);
</script>

Manipulating the document with JavaScript also becomes easier if you use the jQuery plugin or similar, but this is not required

1
  • i changed my code, now he puts the default radiobutton 'no' on, but the div keeps showing on?
    – Jeroenb
    Feb 27, 2015 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.