Using if operators && || in the same condition - javascript

I have this form
<form class="form" method="post">
<input type="text" id="input_what" holder="what" />
<input type="text" id="input_where" holder="where" />
<input type="submit" value="submit" />
</form>
and this script to prevent submitting the form
$('.form').submit(function(e) {
var what = $('#input_what').val();
var where = $('#input_where').val()
if ( what == "what" || what =="" && where == "where" || where == "") {
e.preventDefault();
console.log('prevented empty search');
return false;
}
});
I know that my condition doesn't work, but i need it to work like this
IF (what == "what" OR what == "") AND (where == "where" OR where == "")
have a look at this fiddle to understand why http://jsfiddle.net/pK35e/
the placeholder-script i´m using, needs me to not submit the form for the cases above
using placeholder="attribute" is no solution for me, so can anyone give me a hint how to set this if-condition ?

Uses parenthesis just like in the textual description you made :
if (( what == "what" || what =="") && (where == "where" || where == "")) {
Side remark : You might be interested, for future versions as it's not supported by IE9-, by the placeholder attribute which will make this simpler.

Try this
if ( (what == "what" || what =="") && (where == "where" || where == ""))

IF ((what == "what" ||what == "") &&(where == "where" ||where == ""))

Use parens. The && operator has a higher precedence than the || operator.
if ((what == "what" || what =="") && (where == "where" || where == ""))
http://en.m.wikipedia.org/wiki/Order_of_operations

I believe you need some parenthesis in order to get what you want:
if ( (what == "what" || what =="") && (where == "where" || where == ""))
This means that both
(what == "what" || what =="")
and
(where == "where" || where == "")
has to return true in order for the code within your if statement to be executed. This is actually quite close to your textual example.
--
Just for the understanding of all of this. Your old code would look like this with parenthesis:
if ( (what == "what") || (what =="" && where == "where") || (where == "")) {
Where again, just one of these would have to return true.

Related

why I can not use && in javascript for not blank and not space

I want to check the value is not blank or one empty space so I wrote a code
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>
You can update your condition as below.
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() == "") {
alert("empty");
}
If you want to get alert if OccLocation is not empty then :
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim() != "") {
alert("not empty");
}
Your condition is wrong.
You have to use == instead of !=.
If you use && then both condition should be true to return true, which is ultimately impossible at the same time in this case. Use || instead, this will be evaluated as true if any of the condition is true.
The condition should be:
if (OccLocation.value ==" " || OccLocation.value == "")
Even you can simplify the condition by using String.prototype.trim()
:
The trim() method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
Try
if (OccLocation.value.trim() == "")
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value.trim()== ""){
alert ("empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass" />
You are checking that it is not empty, then alerting that it is empty. I think you mean to check that it is empty. Change your JS to the following:
var OccLocation = document.getElementById("HdnOccLocation");
if (OccLocation.value === " " || OccLocation.value === "")
{
alert ("empty");
}
Your code runs immediately, and the value="" sets it to empty.
Here, I set the value in the markup so it has some, thus it alerts.
var OccLocation = document.getElementById("HdnOccLocation");
console.log(OccLocation.value)
if (OccLocation.value != " " && OccLocation.value != "") {
alert("not empty");
}
<input type="hidden" id="HdnOccLocation" name="HdnOccLocation" value="dd" style="position:absolute;height:20px;color:#000000;text-align:left;font-size:12px;font-style:normal;width:26px;background-color:#00cccc;left:800px;font-weight:normal;top:220px;" class="textClass"
/>

Validate 2 check boxes and 2 text boxes

My goal is user require to choose at least one option from 2 check boxes and 2 text boxes. If user do not select anything, the system will prompt the user to select at least one.
However, right now, the user need to select everything which is not what I want.
Below are my codes..
Help will be appreciate..Thanks! :)
At index.jsp
<form method="post" name="searchform" onsubmit="return validateForm();">
Date: <input name="date" readonly="readonly" />
Number: <input type="text" name="on">
<input type="checkbox" id="completed"> Option A
<input type="checkbox" id="pending"> Option B
<input type="submit" value="Submit">
</form>
At javascript
function validateForm() {
var radio1 = document.getElementById('pending').checked;
var radio2 = document.getElementById('completed').checked;
var on = document.forms["searchform"]["on"].value;
var date = document.forms["searchform"]["date"].value;
if ((radio1 == "") || (radio2 == "") || (on == null || on="") || (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}
}
simply change your outer || to &&
if ((radio1 == "") && (radio2 == "") && (on == null || on="") && (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}
Try this one
if (((radio1 == "") && (radio2 == "")) &&(on == null || on="") && (date == null || date =="")){
alert('Please Choose at least 1 Option');
return false;
}

Javascript Entering Test For Null in JSP

I'm currently trying to fill some fields in my forms. I'm doing a test where if extnReason and extnDt are null, I do nothing. But for some reason, it keeps entering the check and loading my fields with null, which I don't want.
function preloadFields() {
//these values are coming in as null
var extnReason = '<%=extnReason%>';
var extnDt = '<%=extnDt%>';
//set Extension Date blank on load
$('#extnDt').val("");
alert("reason ++++ " + extnReason);
alert("extnDt ++++ " + extnDt);
//it is entering these tests but I don't want them to
if(extnReason != null || extnReason != "null"){
console.log("entered reason");
$('#extnReason').val(extnReason);
}
if(extnDt != null || extnDt != "null") {
console.log("entered extnDt");
$('#extnDt').val(extnDt);
}
}
Any help would be greatly appreciated!
You'll need
if(extnReason != null && extnReason != "null")
instead of
if(extnReason != null || extnReason != "null")
Because if extnReason is 'null' the first condition 'null' != null would return true, so an OR check would evaluate to true and therefore enter the block of code which sets your value.
Same for the other if condition...
Alternative way of preloading your fields: you could also just set the value attribute of your input tag instead of using preloadFields? i.e. something like:
<input type="text" id="extnDt" value="${extnDt != null ? extnDt : ''}" />

document.getElementById('textbox').value stopped working

my code is very simple. I want the user to be able to type in a restaurant name and have my function tell them whether that restaurant serves Coke or Pepsi products. It worked fine an hour ago, but stopped working. Now, it shows the work "Pepsi" no matter what you type in. My guess is that there is something wrong with the if statements.
<html>
<noscript><b><center><font size="16">This app requires JavaScript to be enabled. Enable JavaScript on your browswer to make it work.</font></center></b></noscript>
<center>
<form onsubmit="popproducts()">
<br><br><br><br><br><br><br><br><br>
<input id="textbox" type="text" style="height: 100px; width: 500px" value=""></input>
</br></br></br></br></br></br></br></br></br>
</form>
</center>
<script type="text/javascript">
function popproducts()
{
if(document.getElementById('textbox').value == "Cougars" || "Kane County Cougars" || "Cougars Baseball")
{
document.write('<center><br><font color="#0000FF" size=20></b>Pepsi</b></font></br></center>');
document.write('<br><br><center><form><input type="button" style="height: 100px; width: 100px" value="Back" onClick="history.go(-1);return true;"></form></center></br></br>');
}
if(document.getElementById('textbox').value == "Burge" || "Iowa" || "University of Iowa")
{
document.write('<center><br><font color="#FF0000" size=20><b>Coke</b></font></br></center>');
document.write('<br><br><center><form><input type="button" style="height: 100px; width: 100px" value="Back" onClick="history.go(-1);return true;"></form></center></br></br>');
}
}
</script>
</html>
It's the line:
if(document.getElementById('textbox').value == "Cougars" || "Kane County Cougars" || "Cougars Baseball")
It should be:
if(document.getElementById('textbox').value == "Cougars" || document.getElementById('textbox').value == "Kane County Cougars" || document.getElementById('textbox').value == "Cougars Baseball")
The first part evaluates as true or false depending on what you type, but the second and third will always evaluate as true.
All other answers are fine but here's how I usually do it:
var value = document.getElementById('textbox').value;
if ( /^Cougars|Kane County Cougars|Cougars Baseball$/.test( value ) ) {
...
}
This is your issue:
if(document.getElementById('textbox').value == "Cougars" || "Kane County Cougars" || "Cougars Baseball")
When you have an if statement with the or operator ||, the praser interprets it as if it was:
if(doc....value == "Cougars || "Kane Country Cougars" != false...)
In other words, the if statement is always true because the string "Kane Country Cougars" isn't false. To fix it, you should do this:
var val = document.getElementById('textbox').value;
if(val == "Cougars" || val == "Kane County Cougars" || val == "Cougars Baseball")
You're using the || operator incorrectly. If you want to check if a value equals one of many values, you have to explicitly convey that. For example:
if ( a == b || a == c || a == d )
Doing it the other way will cause the unexpected behavior you were experiencing.
try this,
var value = document.getElementById('textbox').value;
if (value == 'Cougars' || value == 'Kane County Cougars' || value == 'Cougars Baseball')

Verification function for HTML form data

I've created a function in JavaScript to verify an html form data, my code as below:
function checkPetitionForm_ff() {
if (document.petition_form.petition_firstname.value == "FIRST NAME" || document.petition_form.petition_firstname.value == "") {
alert("Please enter your First Name!")
document.petition_form.petition_firstname.focus();
return false;
}
if (document.petition_form.petition_lastname.value == "LAST NAME" || document.petition_form.petition_lastname.value == "") {
alert("Please enter your Last Name!")
document.petition_form.petition_lastname.focus();
return false;
}
if (document.petition_form.petition_age.value == "AGE" || document.petition_form.petition_age.value == "") {
alert("Please enter your Age!")
document.petition_form.petition_age.focus();
return false;
}
if (document.petition_form.state.value == "Select State") {
alert("Please select your state!")
document.petition_form.state.focus();
return false;
}
if (document.petition_form.petition_address.value == "HOME ADDRESS" || document.petition_form.petition_address.value == "") {
alert("Please enter your address!")
document.petition_form.petition_address.focus();
return false;
}
if (document.petition_form.zip.value == "ZIP CODE" || document.petition_form.zip.value == "") {
alert("Please enter your Zipcode!")
document.petition_form.zip.focus();
return false;
}
if (document.petition_form.phone2.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone2.focus();
return false;
}
if (document.petition_form.phone1.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone1.focus();
return false;
}
if (document.petition_form.phone3.value == "PHONE" || document.petition_form.phone1.value == "" || isNumeric(document.petition_form.phone1.value) == false) {
alert("Please enter the complete phone No!")
document.petition_form.phone3.focus();
return false;
}
if (document.petition_form.level.value == "YOUR LEVEL OF EDUCATION") {
alert("Please select your level of education!")
document.petition_form.level.focus();
return false;
}
if (document.petition_form.degree.value == "DEGREE OF INTEREST") {
alert("Please select your degree!")
document.petition_form.degree.focus();
return false;
}
if (!(document.getElementById(edu).checked)) {
alert("Please select Education!")
document.petition_form.edu.focus();
return false;
}
else {
return true;
}
}
The verifications are working good until "phone2" field and will not complete the verification after this.
I'll do appreciate if you can help me and advise how to solve this.
I think you are getting an exception as isNumeric is not a JavaScript Global function. You need to define it in your page (check out Validate decimal numbers in JavaScript - IsNumeric() for a clean implementation of isNumeric).
Also you should surround your method call with exception handling to get better details of the exception.
In that line you're actually checking phone2 only in the first condition, the others are phone1.
document.petition_form.phone2.value=="PHONE" || document.petition_form.phone1.value=="" || isNumeric(document.petition_form.phone1.value)==false
Also be aware that you do the same for phone3.
It looks like a simple copy/paste error. Notice that the petition_form members referenced after phone2 are phone1... this does not make sense. Compare this line against your next validation where all of the members are phone1.
So, this line:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone1.value == "" ||
isNumeric(document.petition_form.phone1.value) == false) {
Should look like:
if (document.petition_form.phone2.value == "PHONE" ||
document.petition_form.phone2.value == "" ||
isNumeric(document.petition_form.phone2.value) == false) {
(Code is lined up in that manner to hilight the differences.)

Categories