skip to Main Content

I am trying to teach myself HTML I am very new but am making headway however I have run into an issue. I want to use a date picker to fill a blank with a string of text.

<form action="/action_page.php">
  <label for="DayOW">Day of the week:</label>
  <input type="date" id="DayOW" name="DayOW">
  <div Id="DayOW">_______________</div>
</form>

Above is what I have, how can I fill the ___________ with MM/DD/YYY as text based on what is selected in the date picker?

2

Answers


  1. To achieve this, you can use JavaScript to update the content of the based on the value selected in the date picker. You’ll need to add an event listener to the date input to detect changes and then update the content of the accordingly.

    <form action="/action_page.php">
      <label for="DayOW">Day of the week:</label>
      <input type="date" id="DayOW" name="DayOW" oninput="updateDate()">
      <div id="output">_______________</div>
    
      <script>
        function updateDate() {
          // Get the value of the date input
          var selectedDate = document.getElementById("DayOW").value;
    
          // Convert the selected date to the desired format (MM/DD/YYYY)
          var formattedDate = new Date(selectedDate);
          var mm = formattedDate.getMonth() + 1; // Months are zero-based
          var dd = formattedDate.getDate();
          var yyyy = formattedDate.getFullYear();
    
          // Update the content of the div with the formatted date
          var outputDiv = document.getElementById("output");
          outputDiv.textContent = mm + '/' + dd + '/' + yyyy;
        }
      </script>
    </form>
    
    Login or Signup to reply.
  2. The date format that you request is the US way of representing the date. If you have a date the US format can be created using the Intl.DateTimeFormat object.

    When you are using a form a really handy way to update a text is by using the <output> element. It can have a name just like the form and the other form fields, so it is easy to refer to.

    document.forms.form01.dayow.addEventListener('change', e => {
      let form = e.target.form;
      let date = new Date(e.target.value);
      let usdate = new Intl.DateTimeFormat('en-US').format(date);
      form.output.value = usdate;
    });
    <form name="form01" action="/action_page.php">
      <label>Day of the week: <input type="date" name="dayow"></label>
      <div><output name="output"></output></div>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search