我需要帮助,以根据选择哪个单选按钮来更改输入文本的背景颜色。如果选择了单选按钮1,则输入文本的背景变为绿色,如果选择了单选按钮2,则背景变为红色,如果选择了单选按钮3,则隐藏输入文本。到目前为止,当选择了收音机3时,我设法隐藏了输入文本。这是一项工作任务,所以我只需要使用javascript。谢谢。
function myFunction2() {
var x = document.getElementById("myDIV2");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<td><input type="radio" name="row-2" value="positive"></td>
<td><input type="radio" name="row-2" value="negative"></td>
<td><input type="radio" onclick="myFunction2()" name="row-2" value="neutral" checked></td>
<td><div id="myDIV2"><input type="text" name="row-2"></div></td>
答案 0 :(得分:0)
我希望这会有所帮助。不要忘记,如果要在onclick
上调用此函数,则必须为要为其运行的所有元素提供该函数。
function myFunction2() {
let selectedRadioValue = document.querySelector('input[type="radio"]:checked').value;
let textBox = document.querySelector('input[type="text"]');
switch (selectedRadioValue) {
case "positive":
textBox.style.visibility = 'visible';
textBox.style.backgroundColor = 'green';
break;
case "negative":
textBox.style.visibility = 'visible';
textBox.style.backgroundColor = 'red';
break;
case "neutral":
textBox.style.visibility = 'hidden';
break;
}
}
/*Calling `myFunction2()` below to set the initial state of the textbox.
Do this because you provided the checked attribute to the `neutral` radio.*/
myFunction2();
<td><input type="radio" onclick="myFunction2()" name="row-2" value="positive"></td>
<td><input type="radio" onclick="myFunction2()" name="row-2" value="negative"></td>
<td><input type="radio" onclick="myFunction2()" name="row-2" value="neutral" checked></td>
<td><div id="myDIV2"><input type="text" name="row-2"></div></td>