我有一组带有选项的无线电输入"其他"有一个文本字段。我的问题是如何在选择其他选项时使文本字段成为必需。
到目前为止我提出的代码::
<form method="POST" action="testPage.php">
<input type="radio" name="option" value="1">Option 1<br>
<input type="radio" name="option" value="2">Option 2<br>
<input type="radio" name="option" value="3">Option 3<br>
<input type="radio" name="option" value="">Other
<input type="text" name="othertext" onchange="changeradioother()">
<input type="submit" value="Submit">
</form>
<script>
function changeradioother(){
var other= document.getElementById("other");
other.value=document.getElementById("inputother").value;
}
</script>
答案 0 :(得分:1)
尝试调用函数when other radio button is clicked
来设置input field to required
:
<script>
function changeradioother(){
var other= document.getElementById("other");
other.value=document.getElementById("inputother").value;
}
function setRequired(){
document.getElementById("inputother").required=true;
}
function removeRequired(){
if(document.getElementById("inputother").required == true){
document.getElementById("inputother").required=false;
}
}
</script>
<form method="POST" action="testPage.php">
<input type="radio" name="option" value="1" onclick="removeRequired();">Option 1<br>
<input type="radio" name="option" value="2" onclick="removeRequired();">Option 2<br>
<input type="radio" name="option" value="3" onclick="removeRequired();">Option 3<br>
<input type="radio" name="option" value="" onclick="setRequired();" id="other">Other
<input id="inputother" type="text" name="othertext" onchange="changeradioother()">
<input type="submit" value="Submit">
</form>
&#13;
答案 1 :(得分:1)
这里有很多不同的方法 将id添加到您的收音机盒中,并将id设置为文本框。
function changeradioother(){
if(document.getElementById("Other").checked ) {
if(document.getElementById("inputtext").value == ''){
alert('input required');
}
}
return false
}
&#13;
<form method="POST" action="testPage.php" onsubmit="return changeradioother()">
<input type="radio" name="option" value="1">Option 1<br>
<input type="radio" name="option" value="2">Option 2<br>
<input type="radio" name="option" value="3">Option 3<br>
<input type="radio" name="option" value="" id="Other">Other
<input type="text" name="othertext" id="inputtext" >
<input type="submit" value="Submit">
</form>
&#13;
答案 2 :(得分:1)
你可以做那样的事情。 通过所有单选按钮检查点击了哪个。
顺便说一下,您没有将id
添加到单选按钮Other
。
var radio = document.querySelectorAll("input[name='option']");
for(var i = 0;i< radio.length;i++){
radio[i].onclick = function(){
if(this.id == "other"){
document.getElementById('otherText').setAttribute("required", true);
}else{
document.getElementById('otherText').removeAttribute("required");
}
}
}
&#13;
<form method="POST" action="testPage.php">
<input type="radio" name="option" value="1">Option 1<br>
<input type="radio" name="option" value="2">Option 2<br>
<input type="radio" name="option" value="3">Option 3<br>
<input type="radio" name="option" id="other">Other
<input type="text" name="othertext" id="otherText">
<input type="submit" value="Submit">
</form>
&#13;