red*_*ian 1 html javascript forms show-hide radio-button
我试图根据用户是选择电话还是电子邮件单选按钮来隐藏或显示联系人表单的电子邮件/电话号码部分,但是我无法弄清楚为什么它对我不起作用。我已经搜索了堆栈溢出和w3Schools,并且可以确定我使用的是正确的语法,但根据单选按钮,它仍然不会显示/隐藏。任何帮助将不胜感激!
的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>
Run Code Online (Sandbox Code Playgroud)
的CSS
#email {
display:none;
}
#phonenumber {
display:none;
}
Run Code Online (Sandbox Code Playgroud)
Java脚本
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"; }
}
Run Code Online (Sandbox Code Playgroud)
checked单击单选按钮组中的单选按钮时,无需检查属性,因为单击将始终将其选中。您可以为此使用通用功能,如下所示:
hide下面给出的课程应用于电子邮件。showHide(this)下面onClick两个收音机的功能的CSS
.hide {
display:none;
}
Run Code Online (Sandbox Code Playgroud)
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');
}
}
Run Code Online (Sandbox Code Playgroud)