Can't get my alerts working properly with a calendar

Viewed 28

function validateForm() {
  var x = document.forms["confirm"].value;
  if (x != "") {
    alert("Thank you for your booking! We look forward to seeing you on soon!");
  } else {
    alert("Please enter a date for your booking!");
  }
}
<form name="confirm" onsubmit="return validateForm()" method="post">
  <input type="date" id="booking" name="booking">
  <input type="submit" value="Book Now">
</form>

I want the alert to say thank you for the booking with any date entered, and please input a date if the box is empty. Thanks!

4 Answers

function validateForm() {
  var date = booking.value;
  if (date) {
    alert(`Thank you for your booking! We look forward to seeing you on ${date}!`);
  } else {
    alert("Please enter a date for your booking!");
    return false;
  }
}
<form name="confirm" onsubmit="return validateForm()" method="post">
  <input type="date" id="booking" name="booking" required>
  <input type="submit" value="Book Now">
</form>

this will work:

function validateForm() {
        var x = document.querySelector('#booking').value;
        if (x) {
            alert("Thank you for your booking! We look forward to seeing you on soon!");
        } else {
            alert("Please enter a date for your booking!");
        }
    }
<form name="confirm" onsubmit="validateForm()" method="post">
        <input type="date" id="booking" name="booking">
        <input type="submit" value="Book Now">
    </form>

2 pointers:

1) Your selector is wrong. You need the value of date input which has id booking.

2) You don't necessarily need to compare with empty string, just do if (x).

function validateForm() {
    var x = document.getElementById("booking").value;
    if (x) {
       alert("Thank you for your booking! We look forward to seeing you on soon!");
    } else {
       alert("Please enter a date for your booking!");  
    }
}

Cause you choose the forms Element, so you should select the "booking" element in form Element.

Can see below. and read this doc https://developer.mozilla.org/en-US/docs/Web/API/Document/forms

    function validateForm(e) {
      var x = document.forms["confirm"];
      let formData = x.elements[0].value;

      if (formData != "") {
        alert("Thank you for your booking! We look forward to seeing you on soon!");
      } else {
        alert("Please enter a date for your booking!");
      }
    }
<form name="confirm" onsubmit="return validateForm()" method="post">
  <input type="date" id="booking" name="booking">
  <input type="submit" value="Book Now">
</form>

Related