首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用单选按钮更改输入文本的bg颜色

使用单选按钮更改输入文本的bg颜色
EN

Stack Overflow用户
提问于 2019-01-25 07:49:51
回答 1查看 250关注 0票数 0

我需要帮助来改变输入文本的背景颜色,这取决于哪个单选按钮被选中。如果选中单选按钮1,则输入文本的背景变为绿色;如果选中单选按钮2,则背景变为红色;如果选中单选按钮3,则隐藏输入文本。到目前为止,当单选3被选中时,我设法隐藏了输入文本。这是一个工作任务,所以我只需要使用javascript。谢谢。

代码语言:javascript
复制
function myFunction2() {
    var x = document.getElementById("myDIV2");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-09 07:12:09

我希望这能帮到你。不要忘记,如果您要在onclick上调用此函数,则必须为您希望为其运行的所有元素提供此函数。

代码语言:javascript
复制
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();
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54357092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档