Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  156] [ 1]  / answers: 1 / hits: 24802  / 10 Years ago, sun, july 6, 2014, 12:00:00

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; }
}

More From » html

 Answers
12

  • 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


[#70302] Thursday, July 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnathanhakeems

Total Points: 487
Total Questions: 129
Total Answers: 100

Location: Fiji
Member since Fri, Nov 13, 2020
4 Years ago
;