javascripthtmlalert

Alert Box for webpage. Javascript/HTML


I'm working on an assignment for school and it's asking me to create an alert for two email addresses being different. What I have works as far as giving an alert when the two emails are different, except that it gives an alert in any other case as well. How do I fix this? Here's what I got:

function alertBox() {
  let email = document.getElementById("email");
  let confirmation = document.getElementById("confirmation");
  if (email != confirmation) {
      alert("Email addresses do not match. Please try again.");
  }
}
<form method="POST">
  <p>
     <label for="email">Email Address:</label>
     <input type="text" name="email" id="email">
  </p>
  <p>
     <label for="confirmation">Confirm Email:</label>
     <input type="text" name="confirmation" id="confirmation">
  </p>
  <p>
      <textarea placeholder="Ask question here" id="textarea"></textarea>
  </p>
</form>

<button onclick="alertBox()">Submit</button>

The assignment says to create a "submit" button and that the form isn't supposed to be submitted to a server, hence no action attribute in the form element and a button instead of input type submit. Any help is appreciated.


Solution

  • compare the .value of the input element instead of the element reference

    function alertBox() {
      let email = document.getElementById("email");
      let confirmation = document.getElementById("confirmation");
     
      if (email.value !== confirmation.value) {
        alert("Email addresses do not match. Please try again.");
      }
    }
    <form method="POST">
      <p>
        <label for="email">Email Address:</label>
        <input type="text" name="email" id="email">
      </p>
      <p>
        <label for="confirmation">Confirm Email:</label>
        <input type="text" name="confirmation" id="confirmation">
      </p>
      <p>
        <textarea placeholder="Ask question here" id="textarea"></textarea>
      </p>
    </form>
    
    <button onclick="alertBox()">Submit</button>