Simple JavaScript not working? - javascript

Why isn't this simple JavaScript validation not working ?? The first condition run through but the second isn't going through ??
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function process(){
var val = document.getElementById('usrIN').value;
var uppVer = val.toUpperCase();
if(val == "" || val == NULL){
alert ("Must fill in input");
}else if (val !== uppVer){
alert("Must be upper case");
}
}
</script>
</head>
<body>
<form type="post" id="frmMain" />
<p>Insert name in upper case <input type="text" maxlength="25" id="usrIN"/></p>
<img src="button.jpeg" >
</form>
</body>

In JavaScript, null is lowercase. Also, your use of == "" will also cover a null or undefined variable. Also, you probably didn't mean to do an else if(), you probably meant to just do a second if if there's no dependency on the former failing for the latter to execute.

NULL is not defined in javascript - use null or undefined.
See here:
http://jsfiddle.net/EZqhN/

Related

if and else statement condition values not being recognized

I am trying to create a block of code that takes a users input value and compares it to a random number generated when the page loads. Right now the if statement in the guess function is displaying regardless of what the value of the conditions are. If they are true it displays the first and third message and if it is wrong it also displays those two. What changes should I make to my code in order to get the if statement to alert the correct response in correlation with the users input value.
<html>
<head>
<script>
window.addEventListener("DOMContentLoaded", setup);
void setup(); {
var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(rNumber1);
}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
var guessedNumber = document.getElementById("guessedNumber");
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else (guessedNumber == rNumber)
alert("You guessed correctly!");
}
</script>
</body>
</html>
Try:
var guessedNumber = document.getElementById("guessedNumber").value;
Also, the Math.random() method always returns a value between 0 and 1 excluding 1. It takes no parameters. Moreover, the way you have passed it parameters using the - sign will subtract the former number from the latter. The way it is used to generate a random number from 1-100 is usually:
rNumber1 = (Math.random()*100+1)
It will multiply the number times 100 and adds 1 to it which ensures that you never get 0. Also, you won't get 101 because it returns a value between 0 and 1 excluding 1.
get the value of from the input box using .value
also, i did not see any open parenthesis in the else statement, and removed the condition in else statement.
setup() is not defined anywhere so i dont know what you are trying to do with that
<html>
<head>
<script>
//window.addEventListener("DOMContentLoaded", setup);
//void setup(); {
//var rNumber1 = Math.random(1-100);
var rNumber = Math.floor(Math.random() * 100) + 1
//}
</script>
</head>
<body>
<form>
<table>
<tr><td><label>Enter Guess:</label></td><td><input id="guessedNumber" type="text" /></td></tr>
<tr><td><label>Is Correct?: </label></td><td><label id="guessResult"></label></td></tr>
<tr><td> </td><td><button type="button" onclick="guess()">Submit Guess</button></td></tr>
</table>
</form>
<script>
function guess() {
console.log(rNumber);
var guessedNumber = parseInt(document.getElementById("guessedNumber").value);
if (guessedNumber != rNumber) {
alert("Your guess is incorrect. Try Again!");
} else if (guessedNumber == NaN) {
alert("Please enter a valid Number");
} else {
alert("You guessed correctly!");
}
}
</script>
</body>
</html>

JavaScript function not recognizing correct password

I was playing an online game where you have to find the password by viewing the page source (or inspect element). I am confused my this line if(el.value == ""+CodeCode+""). el.value is my guess, and it says I can continue if my guess is: ""+CodeCode+"". "+CodeCode+" is defined as: "+CodeCode+" == "0xf.at_hackit"; but i tried "0xf.at_hackit" (with and without quotes but it is not working). I have been stuck on this for 2 hours so please help!
Here is the code of the game which has a javascript function:
<!-- :::::::::::::::::==== GAME STARTS HERE ====::::::::::::::::: -->
<h1>Level 10</h1>
<p>Try not to be fooled</p>
<input id="pw" type="password" />
<br/><input type="button" value="OK" onClick="checkPW()"/>
<script type="text/javascript">var CodeCode = "moo6be";
function checkPW()
{
"+CodeCode+" == "0xf.at_hackit";
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"")
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
<!-- ::::::::::::::::::==== GAME ENDS HERE ====:::::::::::::::::: -->
The code is assigned right after the <script> tag.
The line "+CodeCode+" == "0xf.at_hackit"; does nothing, its just expression that evaluates to false (comparing two different strings), but no assignment, so no side effects.
<script type="text/javascript">var CodeCode = "moo6be"; // <==== HERE
function checkPW() {
"+CodeCode+" == "0xf.at_hackit"; // <==== this does nothing, its just expression that evaluates to false, but no assignment
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"") // <==== this is the same as `if(el.value == CodeCode)`
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
""+CodeCode+"" is the same thing as: "" + CodeCode + ""
CodeCode is assigned right after the tag:
<script type="text/javascript">var CodeCode = "moo6be"; // HERE
function checkPW()
{
"+CodeCode+" == "0xf.at_hackit"; // this does nothing, its just expression that evaluates to false - this is meant to trick you
var el = document.getElementById("pw");
if(el.value == ""+CodeCode+"")
document.location.href="?pw="+el.value;
else alert("Wrong password");
}
</script>
The answer is moo6be.
This is because "+CodeCode+" == "0xf.at_hackit"; has double equals, which just means it is a comparison statement (which will just evaluate to false). It is important to note that this is unrelated to the rest of the program.
The main line here is: if(el.value == ""+CodeCode+"").
Which is: "" (empty string) + CodeCode (moo6be) + "" (empty string).

Weirdest repeat call of function ever

I made a questionnaire form that has a problem with the validation. There are several validating functions, that are called when clicking the submit button. But the first validating function is then called twice. To show the problem, I made a bare bones version that has the same problem. This is the whole source code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Demo Double Call</title>
</head>
<body>
<form name="upssForm" action="submit.php" method="POST" onsubmit="return validateForm()">
A1 <input type="radio" name="A" value="1">
A2 <input type="radio" name="A" value="2"><br>
B1 <input type="radio" name="B" value="1">
B2 <input type="radio" name="B" value="2"><br>
<button type="button" onclick="validateForm()">Validate and submit button</button><br>
<input type="submit" value="Validate and submit input">
</form>
<script>
function checkA() {
var radioA = upssForm.elements['A'];
if (radioA[0].checked == false) {
alert('A1 not checked');
return false;
}
else return true;
}
function checkB() {
var radioB = upssForm.elements['B'];
if (radioB[0].checked == false) {
alert('B1 not checked');
return false;
}
else return true;
}
function validateForm() {
checkA();
checkB();
if ((checkA() == false) || (checkB() == false))
return false;
else
upssForm.submit();
// return true; /* doesn't work either with the submit input */
}
</script>
</body>
</html>
Just click the submit button or the submit input, and see that the alert 'A1 not checked' comes up twice, the second time after the function checkB() is executed. What is causing this, and how do I solve it?
You are calling checkA() twice, once at the beginning of validateForm() and once in the if() statement.
Store the result in a variable, and then check that in the if() statement:
var aResult = checkA();
if(aResult == false) {
}
The answer WildCrustacean gave indeed solved the problem. For the record and future reference, I'll just give the whole function how it should be:
function validateForm() {
var aResult = checkA();
var bResult = checkB();
if ((aResult == false) || (bResult == false))
return false;
else
upssForm.submit();
}
Thanks, bro!
WildCrustacean's answer is correct, so I've edited mine down. Just FYI, you might want to refactor your if statements. For example, if (foo == false) is the same as if (!foo) (although, interestingly, if (foo === false) is not). So, incorporating WildCrustacean's answer and taking out some redundant code:
function checkA() {
var radioA = upssForm.elements['A'];
if (!radioA[0].checked) {
alert('A1 not checked');
}
return radioA[0].checked;
}
//function checkB() { ...
function validateForm() {
var a = checkA();
var b = checkB();
if (a && b) {
upssForm.submit();
}
return false;
}
It's okay that validateForm always returns false, because the only time that affects anything is when the user clicks the input (not the button) while the form is invalid.
Demo: http://jsfiddle.net/5GA5F/2/
In fact, if you don't mind odd-looking code, you can take advantage of Boolean short-circuiting to shrink the code even more:
function checkA() {
var radioA = upssForm.elements['A'];
return radioA[0].checked || alert('A1 not checked');
}
function checkB() {
var radioB = upssForm.elements['B'];
return radioB[0].checked || alert('B1 not checked');
}
function validateForm() {
var a = checkA(),
b = checkB();
return a && b && upssForm.submit();
}
Demo: http://jsfiddle.net/5GA5F/3/
Here's another way to do it:
function validateForm() {
if ((result = (checkA() && checkB()))){
upssForm.submit();
}
return result;
}
This way, your function always returns information on whether it succeeds or not. Another thing to notice here: in JavaScript, assignment statements return the value of the assignment. We didn't have to assign the result value separately because we could call it in the if condition.
One thing to keep in mind: checkB() will only run if checkA() succeeds. If you need them both to execute, assign their values to a variable and then check those variables.

Javascript/HTML - "This page is not loaded within the correct frameset"

Working through a javascript book that wants me to make a simple factorial calculator and I keep getting the error "This page is not loaded within the correct frameset" when I click the calculate button in the code below. Now the code is programmed to throw back this error if it's not in the correct frameset, but my question is why isn't it?
Edit: To clarify, I'm definitely starting off on calcfactorialtopframe.htm.
calcfactorialtopframe.htm
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function calcFactorial(factorialNumber)
{
var factorialResult = 1;
for (; factorialNumber > 0; factorialNumber--)
{
factorialResult = factorialResult * factorialNumber;
}
return factorialResult;
}
</script>
</head>
<frameset cols="100%,*">
<frame name="fraCalcFactorial" src="calcfactorial.htm" />
</frameset>
</html>
calcfactorial.htm
<html>
<head>
<title>Example</title>
<script type="text/javascript">
function butCalculate_onclick()
{
try
{
if (window.top.calcFactorial == null)
throw "This page is not loaded within the correct frameset";
if (document.form1.txtNum1.value == "")
throw "!Please enter a value before you calculate its factorial";
if (isNaN(document.form1.txtNum1.value))
throw "!Please enter a valid number";
if (document.form1.txtNum1.value < 0)
throw "!Please enter a positive number";
document.form1.txtResult.value =
window.parent.calcFactorial(document.form1.txtNum1.value);
}
catch(exception)
{
if (typeof(exception) == "string")
{
if (exception.charAt(0) == "!")
{
alert(exception.substr(1));
document.form1.txtNum1.focus();
document.form1.txtNum1.select();
}
else
{
alert(exception);
}
}
else
{
alert("The following error occursed " + exception.message);
}
}
}
</script>
</head>
<body>
<form action="" name="form1">
<input type="text" name="txtNum1" size="3" /> factorial is
<input type="text" name="txtResult" size="25" /><br />
<input type="button" value="Calculate Factorial" name="butCalculate" onclick="butCalculate_onclick()" />
</form>
</body>
</html>
Yes this is Chrome bug, working Fine in Latest versions of Firefox, IE and Opera :)
My guess is you are loaded calcfactorial.htm into the address bar and not calcfactorialtopframe.htm.
This is a Chrome specific bug.
I did previously try the same code in IE with the same error, although upon a trying it again it appears to be working in IE but still not working in Chrome.

Alert box is not working in function while validating username and password using if condition in javascript

function validate() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==null || x==" ") {
alert("Enter username");
}
if(y==null || y==" ") {
alert("Enter password");
}
}
As Twonky commented, we need some additional information. The code that you posted is just a function. I suppose you have two inputs and a button? Do you want the alerts to show when a user clicks the button and the input fields are empty? If you do, you need to add this function as a callback to onclick event.
More about the events:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events
https://www.bitdegree.org/learn/onclick-javascript
https://www.w3docs.com/snippets/html/how-to-make-button-onclick-in-html.html
Edit: added corrected code and some links for further reading. The mistake was with looking for white space, instead for an empty string (" ", instead of "")
<!doctype html>
<html>
<head>
<title>Welcome</title>
<script>
function validateForm() {
var x=document.getElementById("user").value;
var y=document.getElementById("pass").value;
if(x==="" || x===null) {
alert("Enter username");
};
if(y==="" || y===null) {
alert("Enter password");
};
};
</script>
</head>
<body>
<div>
Username:<input type="text" name="un" id="user"/>
Password:<input type="password" name="ps" id="pass"/>
<input type="submit" onclick="validateForm()"/>
</div>
</body>
</html>
Further articles about these topics:
Stackoveflow thread about whitespace and empty strings
An article about the difference between == and ===
P.S.: I had also changed the element from form to div. Since you are using your function in this case as a security so the user wouldn't submit empty data, this is better for now, since form is submitted with your function call and div isn't. You can check the network tab to see, that the page reloads after the function is executed with form element and is not reloaded with the div element.
if(x === undefined || x === null || x.trim() === '') alert('Please enter a username');
if(y === undefined || y === null || y.trim() === '') alert('Please enter a password');

Categories