So on my portfolio here i made a decent contact form, however with JS i did form validation, now first time i called the function but every time page was loaded it would run alert right away without even touching any inputs, but removing function invocation it fixed the problem and by adding return false to if statements form validation works fine as it alerts me that i need to fill the input which didnt work when i didnt write return false in each if statement. So to sum it up, why does it alert automaticaly when page loads when invoking a function? Why wouldnt form validation work without using return “false” and while i didnt invoke function? Why did it work without return “false” while i invoked a function?
Here’s an example from w3schools i checked out: https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js
And here’s my HTML :
<form name="myForm" onsubmit="return myFunction()">
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" id="exampleFormControlInput1" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleFormControlFirstName">First name</label>
<input type="text" class="form-control" id="exampleFormControlFirstName" name="fname" placeholder="First name">
</div>
<div class="form-group">
<label for="exampleFormControlLastName">Last name</label>
<input type="text" class="form-control" id="exampleFormControlLastName" name="lname" placeholder="Last name">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">Country</label>
<select class="form-control" id="exampleFormControlSelect1">
<option>Bosnia and Herzegovina</option>
<option>Croatia</option>
<option>Serbia</option>
<option>Montenegro</option>
<option>Slovenia</option>
</select>
</div>
<div class="form-group">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Example textarea</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="5"></textarea>
</div>
<button class="btn btn-default">Send</button>
</form>
JS (Example of form validation that works properly):
function myFunction() {
var x = document.forms["myForm"]["email"].value;
var y = document.forms["myForm"]["fname"].value;
var z = document.forms["myForm"]["lname"].value;
if (x == "") {
alert("Please fill it ");
return false;
} else if (y == "") {
alert("Please fill it");
return false;
} else if (z == "") {
alert("Please fill it");
return false;
}
}