Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
168
rated 0 times [  171] [ 3]  / answers: 1 / hits: 20069  / 11 Years ago, wed, january 15, 2014, 12:00:00

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?


More From » html

 Answers
13

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


[#73158] Tuesday, January 14, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;