Saturday, 17 August 2013

Why does the order of Boolean values affect this program?

Why does the order of Boolean values affect this program?

I created a basic program where user input is turned into an alert on
submission. I can't figure out why the program only works as intended if I
use false rather than true as the first condition in my if/else statement.
I'm sure this is very basic but I've failed to find anything of relevance.
After a long search I decided to post the question. Any answers will be
greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;

No comments:

Post a Comment