skip to Main Content

I am trying to assign an click eventlistener to a html option element, I want to display the time picker in a task management project using HTML,CSS and vanilla JAVA-SCRIPT by selecting a choose-date option,How can i resolve this issue using only simple Java-Script?

Here my code:

const chooseDate = document.getElementById("choose-date");
chooseDate.addEventListener("click", () => {
  document.getElementById("date").classList.remove("hidden");
});
body {
  background-color: rgb(143, 134, 134);
}

input,
select {
  position: absolute;
  left: 50%;
  bottom: 50%;
  height: 40px;
  font-size: 20px;
  border-radius: 20px;
}

input {
  bottom: 45%;
  display: none;
}
<select name="selection" id="my-selection">
  <option value="today">today</option>
  <option value="tomorrow">tomorrow</option>
  <option value="choose-date">choose-date</option>
</select>
<input type="datetime-local" name="" id="" />

2

Answers


  1. There is no element with an id of ‘choose-date’. For the getElementById to work you will need to set the id of one of the elements to ‘choose-date’.

    <option value="choose-date" id="choose-date">choose-date</option>
    
    Login or Signup to reply.
  2. You’ll want to attach the event listener to the <select> element and handle the visibility of the date picker based on the selected option. Here’s how you can adjust your code:

    1. Assign an ID to the input element: This makes it easier to select and manipulate the date picker input with JavaScript.

    2. Change the Event Listener: Instead of adding the event listener to an option (which doesn’t work as options don’t handle events directly), attach it to the element and listen for change events.

    3. Update the JavaScript to toggle visibility: Check the value of the selected option in the event listener and toggle the visibility of the date picker accordingly.

    It should look something like this:

    HTML:

    <select name="selection" id="my-selection">
      <option value="today">Today</option>
      <option value="tomorrow">Tomorrow</option>
      <option value="choose-date">Choose Date</option>
    </select>
    <input type="datetime-local" id="date-picker" style="display: none;" />
    

    JS:

    document.getElementById("my-selection").addEventListener("change", function() {
      var datePicker = document.getElementById("date-picker");
      if (this.value === "choose-date") {
        datePicker.style.display = "block";
      } else {
        datePicker.style.display = "none";
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search