Search code examples
javascriptgrails

How to enable DateTime if checkbox is checked?


I'm trying to implement that when a user checks the checkbox it enables the certain field like a DateTime in JavaScript.

For instance, by default, the dateTime is disabled, until a user checks the Checkbox, then the DateTime will be enabled.

This is similar to what I've been searching for, which is used to display text when user checks the checkbox:

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";
  }
}

Checkbox:

<input type="checkbox" id="myCheck" onclick="myFunction()">
    
<p id="text" style="display:none">Checkbox is CHECKED!</p>

Solution

  • You could achieve this by doing something like the following. I've added documentation to the code to offer explanation of how this solution works:

    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>

    Here is a working jsFiddle also