Reputation: 3407
I wrote, what I thought, was a straight forward if statement in JS but it is running incorrectly.
function printLetter(LetterId) {
var studentflag = $("#IsStudent").val();
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
Everytime it runs, the studentflag
var value is correct, but regardless of whether it is true
or false
, it goes into option 1. I am pretty sure I have done true
/false
checks like this before in JS, but do I need to spell it out (studentflag == true)
instead?
Upvotes: 0
Views: 3261
Reputation: 24648
var studentflag = $("#IsStudent").val();//This is a string .. not a boolean
if (studentflag === "true") //therefore this has to be string comparison
Or you can make studentflag
boolean as follows:
var studentflag = $("#IsStudent").val() === "true";
if (studentflag) { ....
Upvotes: 0
Reputation: 531
IMO there should be more context in the question. If submitted solution works for OP that is great, but for others using this as a resource, the accepted solution might not work in all cases.
The value retrieved from an element via JS actually depends on the input itself and its HTML structure. Here's a demo explaining the difference between using .val()
, .attr('val')
, and .is(':checked')
with checkboxes and radios. All of those variants can pull different values from an element depending on its HTML structure and current UI state.
Fiddle : http://jsfiddle.net/h6csLaun/2/
Upvotes: 2
Reputation: 20024
This is known as truthy and falsy Values
The following values are always falsy:
All other values are truthy:
"0"
(zero in quotes), "false"
(false in quotes) like if (studentflag) //being studentflag "false"
, Upvotes: 8
Reputation: 101768
If #StudentFlag
is either "true"
or "false"
, then if(studentFlag)
will always follow the true
route because both are non-empty strings (truthy). You need to do something along these lines:
var studentflag = $("#IsStudent").val();
if (studentflag === "true") {
//do option 1
} else {
//do option 2
}
Upvotes: 3
Reputation: 5283
.val ()
doesn't return a boolean.
Try this instead;
function printLetter(LetterId) {
var studentflag = $("#IsStudent").is (':checked');
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
This is assuming #IsStudent
is a checkbox. If it's not, try this (assuming the value is true
(as a string, not a boolean));
function printLetter(LetterId) {
var studentflag = ($("#IsStudent").val () == 'true')
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
Upvotes: 2