Reputation: 1694
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?
Upvotes: 4
Views: 20980
Reputation: 55
Try this:
var ee = byTitle = byAuthor = startDate = endDate="";
if(ee=="null" || ee.length==0 || !ee)
{
alert("all fields must be filled out");
return false;
}
Upvotes: 0
Reputation: 20014
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 "==".
Upvotes: 8
Reputation: 75
maybe you can like this;
$(function(){
var bytitle = $("input[name=byTitle]").val();
var byAuthor = $("input[name=byAuthor]").val();
var startDate = $("input[name=startDate]").val();
var endDate = $("input[name=endDate]").val();
if( bytitle == '' && byAuthor == '' && startDate == '' && endDate == '')
alert("Enter at least one search parameter!");
});
Upvotes: 1
Reputation: 128791
""
is falsy, so you can simply use:
if (!byTitle && !byAuthor && !startDate && !endDate) {
...
}
This uses the logical NOT operator on your variables (!
) to convert them to boolean values, then return the opposite.
Upvotes: 3
Reputation: 1483
You can use AND in your condition :
byTitle = "";
byAuthor = "";
startDate ="";
endDate = ""
if(byTitle == "" && byAuthor =="" && startDate =="" && endDate == ""){
alert("Enter at least one search parameter!");
return false;
}
Upvotes: 0