javascript if fails - javascript

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

Related

WebForms - Custom Validator No Longer Working

In my WebForms application I have a CustomValidator control. This control executes a JavaScript function that I created. If this function returns false, the form won't submit. This validator is used with the standard RequiredFieldValidator and RegularExpressionValitors.
This used to work perfectly fine, however, now, even if the JavaScript function returns false, the page will still submit. For some reason the CustomValidator is being ignored. As long as the RequiredFieldValidator and RegularExpressionValidator controls pass, the page will submit, even though the JavaScript function displays the errors on submission.
I have debugged the JavaScript function and it is definitely returning false. I didn't use any server side code with my CustomValidator.
JavaScript:
function validateForm() {
if (document.getElementById("DDApplicationID").selectedIndex > 0
&& document.getElementById("div_applicationType").style.display != "none") {
return true;
}
else if (document.getElementById("DDApplicationID").selectedIndex > 0) {
var valid = true;
((validateTrainStation() == false) ? valid = false : valid);
((validateSupportType() == false) ? valid = false : valid);
((validateHomeStatus() == false) ? valid = false : valid);
((validateOtherNationality() == false) ? valid = false : valid);
((validateOtherHomeStatus() == false) ? valid = false : valid);
((validateSortCode() == false) ? valid = false : valid);
((validateCareLeaverMessage() == false) ? valid = false : valid);
return valid; //returns false in JavaScript debugger on Chrome
}
}
Web Forms .aspx
<form id="Application" runat="server">
<asp:CustomValidator ID="CustomValidator1" runat="server" ValidationGroup="AllValidation" ClientValidationFunction="validateForm"></asp:CustomValidator>
<asp:Button ID="SaveLSFApplication" runat="server" Text="Submit Application" OnClick="saveApplication" ValidationGroup="AllValidation" />
</form>
WebForms .aspx.vb
Sub saveApplication(ByVal sender As Object, ByVal e As EventArgs)
If Page.IsValid Then
'--- do logic
End If
End Sub
I know just client side validation isn't good enough, but it's for parts of the form that are non-optional only when a specific criteria has been met, i.e. when a user selects "Other" in drop down box and we want them to put in a reason in a text box.
I've fixed this issue myself. Even though the JavaScript function was returning false, this means nothing in the context of a CustomValidator control. In order to prevent the form from submitting, the CustomValidator evaluates the property IsValid. If IsValid is false, then the form will not submit.
Here is the amended JavaScript function to reflect this change:
function validateForm(sender, args) { //added two function parameters
if (document.getElementById("DDApplicationID").selectedIndex > 0
&& document.getElementById("div_applicationType").style.display != "none") {
return true;
}
else if (document.getElementById("DDApplicationID").selectedIndex > 0) {
var valid = true;
((validateTrainStation() == false) ? valid = false : valid);
((validateSupportType() == false) ? valid = false : valid);
((validateHomeStatus() == false) ? valid = false : valid);
((validateOtherNationality() == false) ? valid = false : valid);
((validateOtherHomeStatus() == false) ? valid = false : valid);
((validateSortCode() == false) ? valid = false : valid);
((validateCareLeaverMessage() == false) ? valid = false : valid);
args.IsValid = valid; //no longer returning valid
}
}
As you can see, I've added two function parameters, sender and args. Then, instead of simply returning valid, I'm now setting the property IsValid of the args parameter to the value of valid. So, if valid is false, then IsValid is false. This IsValid is then evaluated which then prevents the form from continuing to submit.

My console.log keeps saying NaN is false while it isn't

So I have this code and when the user types a number it should log "this is a valid number" in the console and else it should log "this is not a valid number". But my code keeps logging "this is a valid number". And I have to use isNaN.
Please be easy on me, I'm just starting JavaScript.
This is my HTML code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Postcode</title>
<script src="postcode.js">
</script>
</head>
<body>
<form class="form">
<label for="postcode">Postcode: </label>
<input type="text" id="postcode">
</form>
</body>
</html>
And this is my JavaScript code:
window.addEventListener("load", init);
function init() {
alert("Content loaded");
var nameInput = document.getElementById('postcode');
document.querySelector('form.form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
if (nameInput === isNaN || nameInput === "") {
console.log("this is not a valid number!");}
else if (nameInput !== isNaN) {
console.log("this is a valid number!");}
});
}
There's something in javascript called NaN (Not A Number), then there's a function that checks if something is NaN appropriately called isNaN().
You're checking if your variable is the exact same as the isNaN function, which of course it's not, as nameInput is an object, or more correctly a HTML input element.
What you want is probably to get the value of the input, and check if it's "Not A Number", or just an empty string (which seems like an uneccessary check here)
if (isNaN(nameInput.value) || nameInput.value === "") {
Use isNaN(...) to check if a something is Not A Number:
isNaN('a'); // true
And also nameInput refers to a DOM node, get the value (or innerHTML):
isNaN(nameInput.value)
And your full code:
window.addEventListener("load", init);
function init() {
var nameInput = document.getElementById('postcode');
document.querySelector('.form').addEventListener('submit', function (e) {
e.preventDefault();
if (!nameInput.value || isNaN(nameInput.value)) {
console.log("this is not a valid number!");}
else {
console.log("this is a valid number!");}
}
});
}
isNaN is a function. If you do nameInput === isNaN, you check if nameInput is pointing to the function isNaN.
What you want to do, is to call the function: isNaN(nameInput).
Also nameInput is a HTML DOM Element. You first have to get the value from it: nameInput.value
Just do:
if (isNaN(nameInput.value)) {
console.log("this is not a valid number!");}
else {
console.log("this is a valid number!");
}

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

How to display whether Cookie is just enabled or disabled?

I am using javascript code shown below for displaying Cookies either
Enabled
or
Disabled
Code is:
<script>
txt=navigator.cookieEnabled;
document.getElementById("example").innerHTML=txt;
</script>
But this code is just displaying
true
I have no idea how to go ahead.
Please help. Thanks in advance.
navigator.cookieEnabled return true or false. So you can just display what you want on the basis of these values
<script type="text/javascript">
txt=navigator.cookieEnabled;
document.getElementById("example").innerText=(txt==true ?"Enabled":"Disabled");
</script>
please find the below link for checking the cookies enabled state:
http://sveinbjorn.org/cookiecheck
function are_cookies_enabled()
{
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
{
document.cookie="testcookie";
cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
}
return (cookieEnabled);
}
<script>
txt=navigator.cookieEnabled;
document.getElementById("example").innerHTML=(txt==true?"Enabled":"Disabled";
</script>

HTML Checkboxes with Javascript Functions

I'm just trying to get this checkbox to alert a message after it is checked and after it is unchecked by running a function in Javascript. I can get it to display the "checked" message but can't get the "unchecked" alert to come up.
<input type="checkbox" id="chbx" onchange="foo()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
alert("Checked!");
}
else {
alert("UnChecked!");
}
};
</script>
You've got single-equals instead of double-equals in your if statements:
if (checkbox.checked=true) {
should be
if (checkbox.checked == true) {
or just
if (checkbox.checked) {
You are not comparing values using =. Needs to be at least ==, better ===
if(checkbox.checked === true) {}
or, simplified
if(checkbox.checked) {}
You made the commonly made mistake of using a single = this actual sets the checkbox.checked to true. If you want to make a comparison make sure to use a double ==.
Also, there are only two options for a checkbox; so if it's not on it's off:
This is what I would have done:
<input type="checkbox" id="chbx" onchange="checkbox_changed()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function checkbox_changed() {
if (checkbox.checked == true) {
alert("Checked!");
} else {
alert("UnChecked!");
}
}
</script>

Categories

Resources