簡體   English   中英

如果選中復選框,如何啟用日期時間?

[英]How to enable DateTime if checkbox is checked?

我正在嘗試實現,當用戶選中復選框時,它會啟用特定字段,如 JavaScript 中的 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>

您可以通過執行以下操作來實現此目的。 我在代碼中添加了文檔以解釋此解決方案的工作原理:

 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>

這也是一個有效的 jsFiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM