Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

        <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>

         <script>
         function alertBox() {
            let email = document.getElementById("email");
            let confirmation = document.getElementById("confirmation");
            if (email != confirmation) {
                alert("Email addresses do not match. Please try again.");
            }
         }
         </script> ```

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading