我需要帮助来根据选择的单选按钮更改输入文本背景颜色。如果选择单选按钮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>
我希望这有帮助。不要忘记,如果你打算在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>