gpt4 book ai didi

javascript - 使用 Javascript 隐藏或显示表单元素,部分工作

转载 作者:行者123 更新时间:2023-11-30 19:50:22 25 4
gpt4 key购买 nike

只有最后一对单选按钮可以显示last name 字段,当subscribe 被点击时。

目标是每当选择一个或多个subscribe 时,总是显示last name 字段。当没有选择unsubscribe 时,last name 字段被隐藏。单击各种单选按钮应该会产生这些结果。提前致谢。

简单的 HTML 表单

<form>
Adhoc <br>
<input class="subscribe" type="radio" name="news_adhoc" onClick="test();"> subscribe <br>
<input class="unsubscribe" type="radio" name="news_adhoc" onClick="test();"> unsubscribe <br>
<hr> news_newsletter <br>
<input class="subscribe" type="radio" name="news_newsletter" onClick="test();"> subscribe <br>
<input class="unsubscribe" type="radio" name="news_newsletter" onClick="test();"> unsubscribe <br>
<hr>
<input type="text" name="first_name" placeholder="First Name">
<input type="text" name="last_name" id="IdLastName" placeholder="Last Name" style="display:none">
<input type="text" name="email" placeholder="Email">
<hr>
</form>

编写脚本并感谢 Randy Casburn 之前提供的帮助。

<script type = "text/javascript" >
function test() {
var subscr = document.getElementsByClassName("subscribe");
var unsubscr = document.getElementsByClassName("unsubscribe");
var lastName = document.getElementById("IdLastName");

for (var i = 0; i < subscr.length; i++) {

if (subscr[i].checked) {
lastName.style.display = "";
} else {
lastName.style.display = "none";
}
}
}

最佳答案

尝试(你写了名字,但是你的代码片段显示/隐藏了姓氏——所以我展示了如何为姓氏做这件事——改变这个变化 var lastName = document.getElementById("2");var lastName = document.getElementById("1"); (我只编辑 JS 代码 - HTML 不变)

function test() {
var subscr = document.getElementsByClassName("subscribe");
var lastName = document.getElementById("2");
lastName.style.display = "none";

let show=false;

for (var i = 0; i < subscr.length; i++) {
if(subscr[i].checked) show=true;
}

if(show) lastName.style.display = "";
}
<form>
Adhoc <br>
<input class="subscribe" type="radio" name="news_adhoc" onClick="test();"> subscribe <br>
<input class="unsubscribe" type="radio" name="news_adhoc" onClick="test();"> unsubscribe <br>
<hr> news_newsletter <br>
<input class="subscribe" type="radio" name="news_newsletter" onClick="test();"> subscribe <br>
<input class="unsubscribe" type="radio" name="news_newsletter" onClick="test();"> unsubscribe <br>
<hr>
<input type="text" name="first_name" id="1" placeholder="First Name">
<input type="text" name="last_name" id="2" placeholder="Last Name" style="display:none">
<input type="text" name="email" id="3" placeholder="Email">
<hr>
</form>

关于javascript - 使用 Javascript 隐藏或显示表单元素,部分工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54546218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com