简体   繁体   English

Javascript 隐藏文本字段单选按钮

[英]Javascript Hidden Text Field Radio Button

I have a function that is only halfway working right now.我有一个功能现在只工作了一半。 My goal is to have a hidden text box appear in the form if a specific radio button is selected and if it is unselected for the text box to disappear again.我的目标是如果选择了特定的单选按钮,则在表单中显示一个隐藏的文本框,如果取消选择该按钮,文本框将再次消失。 My script is only showing the hidden field when the specific radio button is selected, but when I select a different radio button it does not hide it again.我的脚本仅在选择特定的广播按钮时显示隐藏的字段,但是当我选择另一个无线电按钮时,它不会再次隐藏它。 Here is the function:这是功能:

function showHideOther() {
        var radioButton = document.getElementById("master");
        var text = document.getElementById("dependent");
if (radioButton.value = "Other") {
            text.style.display="block";
        } else {
            text.style.display="none";
        }
    }

How would I alter this function to get the text field to hide when the radio button is no longer selected?当不再选择单选按钮时,我将如何更改此功能以使文本字段隐藏?

if (radioButton.value = "Other") { needs to be if (radioButton.value === "Other") { , and you'll need a reference to which radio button was actually clicked, so you'll probably want to pass the event and get e.target : if (radioButton.value = "Other") {需要是if (radioButton.value === "Other") { ,并且您需要参考实际单击的单选按钮,因此您可能想要传递事件并获得e.target

 function showHideOther(e) { var radioButton = e.target var text = document.getElementById("dependent"); if (radioButton.value === "Other") { text.style.display="block"; } else { text.style.display="none"; } }
 #dependent { display: none; }
 <label for="other"><input onchange="showHideOther(event)" id="other" name="a" value="Other" type="radio"/>Other</label> <label for="master"><input onchange="showHideOther(event)" id="a1" name="a" value="Something" type="radio"/>Something</label> <div id="dependent">The text</div>

radioButton.checked property will be helpful for hide and show radioButton.checked 属性将有助于隐藏和显示

        var radioButton = document.getElementById("master");
        var text = document.getElementById("dependent");
if (radioButton.value == "Other" && radioButton.checked) {
            text.style.display="block";
        } else {
            text.style.display="none";
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM