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

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')

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"
/>

Common javascript form validation not working

I've been trying to use the following javascript code to validate several fields on a contact form. The validation works for the first item being validated, the name field, but not the second, the email field. If the name field is filled in, the validation seems to skip over the email field check when it's blank and the form submits.
function validateForm()
{
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
else if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
else
{
return( true );
}
}
Here is the HTML on the contact form:
<FORM name="contact" METHOD="POST" ACTION="thankyou.php" onsubmit="return validateForm()">
<input type="checkbox" name="newsletter" value="YES" width="30" height="30"> Check the box to subscribe to Herb's Newsletter
<input type="text" class="form-control" size=20 name="name" placeholder="Your name" />
<input type="email" class="form-control" name="email" placeholder="Email Address" />
<input class="btn btn-theme btn-subscribe" type="submit" value="Send" />
</form>
Thank you
You seem to be using empty function in your if clauses which doesn't seem to be defined nor it is part of the standard javascript functions. Try getting rid of it:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "") {
alert("Please enter your name.");
document.contact.name.focus();
return false;
} else if (ema == null || ema == "") {
//Check if the email is missing
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
} else {
return true;
}
}
And here's a live demo.
In your code you use else if statement.
Basically what you code does is:
check name -> if that is falsy check email -> if that is falsy move into else condition.
But when the name is true, the if statement will not move to else conditions because it it already satisfied. So if you want to check both, you either separate the statements and make a 5 separate ifs, make it a switch statement or you create one long check. For example:
if ((n == null || n == "" || empty(n)) || ( ema == null || ema == "" || empty(ema) ))
{
alert("Something is missing");
return false;
}
else
{
return( true );
}
or you use multiple ifs:
function validateForm() {
var n = document.contact.name.value;
n = n.trim();
var ema = document.contact.email.value;
ema = ema.trim();
//Check if the name is missing
if (n == null || n == "" || empty(n))
{
alert("Please enter your name.");
document.contact.name.focus();
return false;
}
//Check if the email is missing
if ( ema == null || ema == "" || empty(ema) )
{
alert( "Please enter your email address." );
document.contact.email.focus();
return false;
}
return( true );
}
The latter will always return true unless one of the if statements is triggered.
And see answer below about the empty() thing. I don't know what that is and if it messes anything up.

complex if statement runs code regardless of condition output

JS
if (isNaN(BDyear) == true || isNaN(BDmonth) == true ||
isNaN(BDday) == true || BDday.length != 2 ||
BDmonth.length != 2 || BDyear.length != 4)
{
document.getElementById("BDyear").value = ''
document.getElementById("BDmonth").value = ''
document.getElementById("BDday").value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false BDcheck = false
}
HTML
<tr>
<td>שנת לידה</td>
<td>
<input class="text" id="BDyear" maxlength="4" style="width:8%" />&nbsp/&nbsp
<input class="text" id="BDmonth" maxlength="2" style="width:5%" />&nbsp/&nbsp
<input class="text" id="BDday" maxlength="2" style="width:5%" />
<br />
<p id="bderror" style="position:absolute; top:70%; color:red; font:65% arial; display:none">תאריך לידה לא תקין</p>
<p id="bderroryoung" style="position:absolute; top:70%; color:red; font:65% arial; display:none">חובה להיות מעל גיל 13</p>
</td>
</tr>
the script part runs regardless whether i put in the inputs a number or words, with any length and i don't understand why is it running, but i'm suspecting it's the "isNaN" function that is not working correctly from different tries and setups. it's supposed to find out if the content entered is only a numric value that is in the proper length for dd/mm/yyyy and if it's all false it's supposed to leave everything as is and BDcheck var to be true so the next if statement will run
Any suggestions?
Make sure BDyear, BDday and BDmonth actually contain values; you may need to use document.getElementById("BDyear").value inside the isNaN functions. The value is also probably a string, so you may want to try first casting it to a number before checking isNaN like this: isNaN(Number(document.getElementById("BDyear").value)).
Also, isNaN returns a Boolean, so comparing it to true is redundant. You can just write it like if (isNaN(BDyear) || isNaN(BDmonth) || isNaN(BDday) || BDday.length != 2 || BDmonth.length != 2 || BDyear.length != 4), possibly with the changes I just suggested.
Ultimately, the code could look like this:
//assuming BDstate and BDcheck variables are already defined
var year = document.getElementById("BDyear");
var month = document.getElementById("BDmonth");
var day = document.getElementById("BDday");
if (isNaN(Number(year.value)) || isNaN(Number(month.value) || isNaN(Number(day.value)) || day.value.length != 2 || month.value.length != 2 || year.value.length != 4)
{
year.value = ''
month.value = ''
day.value = ''
document.getElementById("bderror").style.display = "inline"
BDstate = false
BDcheck = false
}
Also, instead of checking that the string length of month is 2 characters, you may want to check whether the numeric value is between a valid range. For example, a user would currently have to enter "06" (without an leading or trailing spaces, btw) in order for the check to succeed, whereas they could enter " 6 " if you were actually checking that the numeric value is within a valid range like (Number(month.value) >= 1 && Number(month.value) <= 12). The same goes for the day and year.

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;
}

Using if operators && || in the same condition

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.

Categories