【问题标题】:textbox not hiding with checkbox click (javascript)文本框不通过复选框单击隐藏(javascript)
【发布时间】:2020-01-30 16:53:38
【问题描述】:

我有一个文本框,如果未选中复选框,我希望在单击复选框时显示该文本框并消失,但是我的代码当前在页面加载时显示文本框,但是一旦您选择然后取消选择复选框,它就会消失应该的。有什么想法吗?

Javascript:

function TMDFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("tmd_checkbox");
  // Get the output text
  var text = document.getElementById("test");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true) {
    text.style.display = 'block';
  } else {
    text.style.display = 'none';
  }
}
<input type="checkbox" class="product" name="targetedmobiledisplay" value="0.08" id="tmd_checkbox" onclick="TMDFunction()">
Targeted Mobile Display
<br> 
Test: <input id="test" type="text" value="0.00" data-total="0" />

【问题讨论】:

  • 只需在文本框中添加简单的 CSS 以将其设置为不显示...#test{display:none} 或调用 TMDFunction() onload 页面
  • 旁注; text.style.display = (checkBox.checked ? 'block' : 'none');

标签: javascript jquery html checkbox textbox


【解决方案1】:

是的,简单,添加你想要的样式作为默认样式,例如,你想要display: none,所以它被插入到HTML中。

function TMDFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("tmd_checkbox");
  // Get the output text
  var text = document.getElementById("test");

  // If the checkbox is checked, display the output text
  if (checkBox.checked == true) {
    text.style.display = 'block';
  } else {
    text.style.display = 'none';
  }
}
<input type="checkbox" class="product" name="targetedmobiledisplay" value="0.08" id="tmd_checkbox" onclick="TMDFunction()"> Targeted Mobile Display
<br> 
Test: 
<input id="test" type="text" value="0.00" data-total="0" style="display:none;" />

【讨论】:

    【解决方案2】:

    TMDFunction() 仅在单击复选框时运行。最初,当页面加载时,该函数没有被调用。

    您可以尝试在页面加载时隐藏文本框document.ready

    $( document ).ready(function() {
       var text = document.getElementById("test");
      test.style.display = 'none';
    });
    

    一旦页面加载,此功能将隐藏文本框。

    【讨论】:

    • 如何隐藏它旁边的文字?我应该添加到标签并放在函数内吗?
    • 将文本和文本框包裹在 &lt;div&gt; 中,并在页面加载时隐藏
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多