【问题标题】:How to enable DateTime if checkbox is checked?如果选中复选框,如何启用 DateTime?
【发布时间】:2018-09-04 20:35:08
【问题描述】:

我正在尝试实现这一点,当用户选中复选框时,它会启用特定字段,例如 JavaScript 中的 DateTime。

例如,默认情况下 dateTime 是禁用的,直到用户选中 Checkbox,然后 DateTime 才会启用。

这类似于我一直在搜索的内容,用于在用户选中复选框时显示文本:

function myFunction() {
  // Get the checkbox
  var checkBox = document.getElementById("myCheck");
  // Get the output text
  var text = document.getElementById("text");

  // 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" id="myCheck" onclick="myFunction()">
    
<p id="text" style="display:none">Checkbox is CHECKED!</p>

【问题讨论】:

  • 请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。
  • 你能展示你的 HTML 吗?
  • 所以设置 disabled 属性?

标签: javascript grails


【解决方案1】:

您可以通过执行以下操作来实现此目的。我在代码中添加了文档以解释此解决方案的工作原理:

var yourCheckbox = document.querySelector('#myCheck');
var yourDateField = document.querySelector('#yourDateField');

// This function will update the date field's enabled/disabled
// attribute, depending on if the yourCheckbox is checked
function updateYourDateField() {
    
    if(yourCheckbox.checked) {
       yourDateField.disabled = true;
    }
    else {
       yourDateField.disabled = false;
    }
}
   
// Add an event listener to the change event, that causes
// the date field to be enabled/disabled when ever the checkbox
// is clicked and the value changes
yourCheckbox.addEventListener('change', function() {
       
   updateYourDateField();
})
 
// Call this to ensure your date field is in correct state
// when the script is first run
updateYourDateField();
<form>
  <div>
    <label>Disable/Enable control</label>
    <input id="myCheck" type="checkbox" />
  </div>
  <div>
    <label>The date field</label>
    <input id="yourDateField" type="date" />
  </div>
</form>

这是working jsFiddle also

【讨论】:

  • 嗯,这是一个非常简单易懂的快速响应。谢谢。
  • 我想知道您输入的日期是否可以存储在数据库中。谢谢
  • @Cha-LeeChew 是的,它可以添加到数据库中,但这需要更多细节。或许您可以为此再问一个问题?
  • 我已经添加了关于这个问题的新问题。感谢您的指导。
  • 我是新手,你能告诉我如何接受这个作为答案吗? :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
  • 2017-09-08
  • 2013-12-06
  • 2014-07-11
  • 1970-01-01
相关资源
最近更新 更多