ok so before I ask my question or post any code i'm going to explain what i'm trying to do.
I am using windows 10 and XAMPP. I am trying to create a register form which is mostly made of HTML and PHP however I have decided that it makes more sense to make the browser check if the password chosen by the user and it's confirmation match before even submitting it to the server rather than doing the same with PHP on backend.
for this purpose I have decided to use a simple JS code.
I am trying to bind the text written in the password field and confirmation field to two variables and then use if to check if they match however even when I intentionally type wrong confirmation, the form submits.
I tried using google chrome console to find out why. turns out that the variable I am using for password and confirmation are always equal to "" and since "" = "" the form always submits.
when I type in the console "btn" it shows me the correct HTML element which means that DOM was loaded before JS so that can't be the problem also I have written my js codes after the HTML form.
also I have noticed that in the console when I type " password.value" it always shows correctly what I have written in the field.
is it because I am writing all this in a php file? if so how can I mix JS and PHP to prevent this problem. I will post the form and the js code here.
EDIT: I undertand that my question is a bit vague so I need this edit, I know that I am not stopping the script so the form submits anyways BUT I must get the alert because I intentionally make so that password and confirm don't match!
var btn = document.getElementById('3');
btn.addEventListener('click' , function(){
var pa = document.getElementById('password').value;
var co = document.getElementById('confirm').value;
if(pa !== co)
{
alert("password and confirmation must match!");
}
});
<form method="post">
<label for="email">Please enter your valid email address:</label>
<input type="email" name="email" placeholder="enter your email address" required>
<br>
<br>
<label for="password">Please choose a password:</label>
<input type="password" name ="password" placeholder="enter your password" required id="pass">
<br>
<br>
<label for="confirm">Please confirm your password:</label>
<input type="password" name="confirm" placeholder="confirm your password" required id="conf">
<br>
<label for="agreement">by registering on this website i agree to the <a href="#">terms and conditions!</a></label>
<input type="checkbox" name="agreement" id="">
<br>
<input type="submit" value="Sign Up!" id="3">
</form>