Why does the order of Boolean values affect this program? - javascript

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;

The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}

To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.

Because your input is a string. And string == true will be false.
You can set breakpoints to check them.

Related

How to add more than 2 conditions in an If/Else statement in Javascript?

Me again.
So I have been working on this basic search functionality where I am comparing the value entered as text with a list of other values and doing an action based on it.
In simpler words. I am making a search where the logic compares the value with other strings and if the comparison is successful then show and hide and vice versa if the condition is false.
Now the other condition i want to implement is that when the text bar(where the user will enter the value) is empty then both the divs should be shown. Below is my code for this:
HTML where I am getting the value from: - Im using the onchange to get the value - oninput is not working :(
<label>Find your location:</label>
<input type="text" class="form-control" id="search_input" placeholder="Type address..."
onChange="myFunction()"/>
And This is my JS code
<script>
function myFunction() {
var inzone = document.getElementById("inzone");
var outzone = document.getElementById("outzone");
if(document.getElementById("search_input").value == null
||document.getElementById("search_input").value == "")
{
outzone.style.display = "";
inzone.style.display = "";
}
else if (document.getElementById("search_input").value === 'something something')
{
outzone.style.display = "none";
inzone.style.display = "";
}
else {
inzone.style.display = "none";
outzone.style.display = "";
}
document.getElementById("search_input").value == null will never be true. The value property of an HTMLInputElement is always a string. It may be "", but not null or undefined (the two things == null checks).

Check if value entered is a valid integer

I want to check if the value entered by the user is a valid integer using jquery
I have tried this code but it always seems to return true:
if ((manageridEntered === "") || ($.isNumeric(manageridEntered))) {
success = false;
}
You could use classic JavaScript :
var isNumber = Number.isInteger(yournumber);
Or if you want to check if it isn't (without using !) :
var isNaN = Number.isNaN(yournumber);
console.log(Number.isInteger(0.1)); // false
console.log(Number.isInteger(1)); // true
console.log(Number.isInteger(-100000)); // true
console.log(Number.isInteger(Math.PI)); // false
console.log(Number.isInteger(-Infinity)); // false
console.log(Number.isInteger(true)); // false
console.log(Number.isInteger(NaN)); // false
console.log(Number.isInteger(0)); // true
console.log(Number.isInteger("10")); // false
No need to use jquery
You can use javascript isNaN()
isNaN() accepts decimal numbers also
return !isNaN(manageridEntered))
or
You can use plain javascript regex here to match only digits
return new RegExp('^\\d+$').test(manageridEntered))
You can use vanilla JavaScript:
success = !manageridEntered.length || parseInt(manageridEntered) == manageridEntered;
Use regex
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
}
Example taken from checking if number entered is a digit in jquery
$('.submitBtn').click(function() {
var Number = $('#Number').val();
if ((Number === "") || ($.isNumeric(Number))) {
alert('Valid NUmber');
}else{
alert('Not Valid NUmber');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form method="post" action="">
Inateger Value: <input type="text" name="Number" id="Number" />
<input type="submit" value="Submit" class="submitBtn">
</form>
isNumeric is checking for a number (which could be wrapped in a string too), not an integer. Beside that isNumeric() is not always returning true like you can see in the following snippet using JQuery 2.1.1.
console.log($.isNumeric('a')); // false
console.log($.isNumeric('1')); // true
console.log($.isNumeric(1)); // true
console.log($.isNumeric(1.5)); // true
console.log($.isNumeric('1.5')); // true
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Please try this:
if(Math.floor(manageridEntered) == manageridEntered && $.isNumeric(manageridEntered)){
//code here
}
Using Regex you can achieve it see below code
$(document).ready(function () {
$("#button").on("click", function () {
var patt = new RegExp("^[0-9]*$");
if (patt.test($("#number").val())) {
alert("true")
} else {
alert("false")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="number" />
<input type="button" id="button" value="Check"/>
returns true if it's an integer
if(manageridEntered == parseInt(manageridEntered))

Why is this button not working?

I've recreated a problem in one of my projects. I have no idea why this doesn't work. It seems to fail when I add the textbox. For some reason, using a textbox is creating this error.
<input type="text" id="apple">
<input type="button" value="Go" id="banana">
<script>
var element = document.getElementById('apple');
var element2 = document.getElementById('banana');
element2.addEventListener("click", function(){
var test = element.value;
if (typeof test != "number"){
alert();
}
});
</script>
Fiddle: https://jsfiddle.net/3mp0869s/8/
element.value; will return always string, so the condition will be never acheived, you should parse the value returned. or if you want just to check if the value of input is a number you can use isNaN() function :
if(isNaN(element.value)){
alert('is not a number');
}else{
alert('is a number');
}
NOTE : you can also use input with type number so you don't have to check.
Hope this helps.
Try this code:
if (isNaN(test)){
alert("Not a number");
}
Here is your updated jsfiddle : https://jsfiddle.net/3mp0869s/9/

simple Form validation with javascript

I'm trying to create a simple HTML form & i want to use javascript to validate the values.
Here's the form tage:
<form action="" onSubmit="return formValidation();" method="Post" name="form">
Here's a part of the HTML form:
<label for="text">my text:</label>
<input type="text" name="text">
<div id="error"></div>
<input type="submit" value="submit">
& here's the formValidation() function:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
& here's the textValidation() code:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
return true;
}
The problem is when i enter an invalid text, it shows the error but hitting the submit button again has no effect, even if i change the text.
i've used alert() & it worked fine.
what am i doing wrong?
You're setting the error text but you don't clear it so it just sticks around. Also, you have to return true in the if statement on your formValidation function otherwise it will always return false.
You can clear the message like this:
function textValidation(txt, mn, mx) {
var txtlen = txt.value.length;
if (textlen == 0 || txtlen <=mn || txtlen > mx ) {
document.getElementById('error').innerHTML = '<h6 style="color: red;">text is invalid</h6>';
return false;
}
document.getElementById('error').innerHTML = "";
return true;
}
Since formValidation always returns false, it will never allow the form to submit. That's fine for testing your JS, but later you'll want to use something like this:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
return true;
}
return false;
}
You can write the form validate function like this
function formValidation() {
var mytext=document.form.text;
//if the variable boolval is initialized inside double quotes it is string now it is bool variable
var boolval=false;
if (textValidation(mytext, 3, 20)) {
boolval=true;
}
return boolval;
}
if textvalidation is true then it will initialize true to boolval or this function will return boolval false as we initialized before[which is default]
Your function formValidation() is always going to return false, regardless of the result of your conditional statement.
Consider your code, corrected in some ways:
function formValidation() {
var mytext=document.form.text;
if (textValidation(mytext, 3, 20)) {
}
return false;
}
If the function textValidation(mytext, 3, 20) is false, formValidation() returns false. If textValidation(mytext, 3, 20) is true, well... the body of the if statement executes, which is empty, and then formValidation returns false.
Additionally, there are also a number of mismatched parentheses and other syntax related issues in your code. Since Javascript is inherently flexible, you might miss these things in practice. I suggest using JSHint to validate and improve the general quality and design of your Javascript code.

javascript if fails

I do not see where my error is, If there is any
<!DOCTYPE html> <html> <head>
<script type="text/javascript">
//http://stackoverflow.com/questions/10251149/using-javascript-to-detect-google-chrome-to-switch-css
//provera brosera
function check_chrome_ua() {
var ua = navigator.userAgent.toLowerCase();
var is_chrome = /chrome/.test(ua);
alert("func check_chrome_ua() " + is_chrome);
return is_chrome;
}
//promena nadpisa
function check() {
//alert("check1");
var check = check_chrome_ua();
alert("var check " + check + "; func check_chrome_ua() " + check_chrome_ua());
if (check == "false") {
alert("change text");
document.getElementById("opomena").style.color = "red";
document.getElementById("opomena").innerHTML = 'Warning you are not using Google Chrome';
}
}
</script>
</head>
<body onmousemove="check()">
<div id="opomena">Thank you for using Google Chrome.</div>
</body>
</html>
Popups on Google Chrome popup says true, on Firefox says false
popup "change text" does not display in Firefox tho var check is false.
Thank you in advance for advice
Change
if (check == "false") {
to
if (!check) {
or
if (check == false) {
if you really want to check for the boolean value, false.
The regexp, test method which you call at /chrome/.test(ua) returns a boolean, but check == "false" is comparing that boolean to a string. The two are not equal.
In JavaScript, == is permissive when it comes to comparing strings to objects, but not as permissive as Perl's eq operator.
0 == false
false == false
"false" == [false]
false != "false"
0 != "false"
It's a good habit to try and use !== and === which are well-defined operators to compare primitive values.
You have to check for boolean value false, not "false" (it's a string).
Only if (!check) would be enough (or more verbose version if (check == false) ).

Categories

Resources