Search code examples
javascripthtmlformsradio-buttonshow-hide

Show/hide fieldset based on radio button using Javascript


I'm trying to have the email/phone number section of a contact form hidden or visible depending on whether the user picks the phone or email radio button, but I cannot figure out why it is not working for me. I've searched through stack overflow & w3Schools, and I'm pretty certain I'm using the correct syntax but it will still not show/hide depending on the radio buttons. Any help would be hugely appreciated!

HTML

<form name="contactForm" id="contactForm" method="post" action="result.php">
                <fieldset>
                    <!-- Client's contact details -->
                    <legend>Contact Details</legend>
                        <label for="fullname">Full Name:</label>
                        <input type="text" name="contact" id="fullname" required>

                        <label>Preferred contact method:</label>
                        <input type="radio" name="contact" value="rdoPhone" id="rdoPhone" checked="checked" onclick="cPhone()" >Phone
                        <input type="radio" name="contact" value="rdoEmail" id="rdoEmail" onclick="cEmail()" >Email

                        <label for="phonenumber">Phone Number:</label>
                        <input type="text" name="contact" id="phonenumber">
                        <label for="email">Email:</label>
                        <input type="text" name="contact" id="email">
                </fieldset>
</form>

CSS

#email {
display:none;
}       
#phonenumber {
    display:none;
}

Javascript

function cPhone() {
if (document.getElementById("rdoPhone").checked)
{ document.getElementById("phonenumber").style.display = "block"; }
}

function cEmail(){
if (document.getElementById("rdoEmail").checked)
{ document.getElementById("email").style.display = "block"; }
}

Solution

    • Since phone number is checked by default, you should not hide it initially.
    • You don't have to check for the checked property on click of a radio in a radio button group, because a click will always select it.

    You can use a common function for this purpose as follows -

    • apply the class hide given below initially for the email.
    • call the function showHide(this) given below onClick of both radios

    css

    .hide {
     display:none;
    }
    

    js

    function showHide(elm) {
     var phone = document.getElementById("phonenumber");
     var email = document.getElementById("email")
     if(elm.id == 'rdoPhone'){
        phone.classList.remove('hide');
        email.classList.add('hide');
     }
     else
     {
        phone.classList.add('hide');
        email.classList.remove('hide');
     }
    }
    

    Demo