HTML form look:
<form action="search" id="searchForm" onsubmit="return validateSearch()">
<input type="text" name="byTitle" pattern="[a-zA-Z0-9]+" placeholder="Enter a word from title">
<input type="text" name="byAuthor" pattern="[a-zA-Z]+\s[a-zA-Z]+" placeholder="First-name Last-name"> <!-- pattern="\w+ \w+" -->
<input id="startDate" name="startDate" type="date">
<input id="endDate" name="endDate" type="date">
<input type="submit" name="submit" value="Submit">
</form>
Javscript validating function:
function validateSearch() {
var byTitle = document.getElementById('searchForm').byTitle.value;
// alert(byTitle);
var byAuthor = document.getElementById('searchForm').byAuthor.value;
// alert(byAuthor);
var startDate = document.getElementById('searchForm').startDate.value;
//alert(startDate);
var endDate = document.getElementById('searchForm').endDate.value;
//alert(endDate);
if(byTitle == byAuthor == startDate == endDate == ""){
alert("Enter at least one search parameter!");
return false;
}
}
Now, if I leave all form fields empty/unfilled and press submit, alert("Enter at least one search parameter!");
message should pop-up, but it doesn't. Wanted to see what are the values of each field I have inserted alert
after each field reading, and they are all same, empty string/blank. So, why is then that if condition
not seeing them as same, empty fields?
Your issue is here:
wrong
if(byTitle == byAuthor == startDate == endDate == ""){
correct
if(byTitle === "" && byAuthor ==="" && startDate ==="" && endDate === ""){
Javascript has a simpler way to evaluate if a value is null, empty string or 0 by only evaluating the variable:
if(!byTitle && !byAuthor && !startDate && !endDate ){
Another advise I wanted to share is to use "===" instead of "==".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With