Reputation: 367
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"; }
}
Upvotes: 2
Views: 26378
Reputation: 9
It is faster to apply it directly in javascript:
$('#id-element').css('display', 'block');
$('#id-element').css('display', 'none');
Upvotes: 0
Reputation: 43156
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 -
hide
given below initially for the email.showHide(this)
given below onClick
of both radioscss
.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');
}
}
Upvotes: 5