9

When I get a value or set a value (from the server side, for example) for an input that is a boolean type it comes as "True" or "False" instead of true or false.

For example:

//"True"
var isDated = $('.someClass').val();


//will not pass because isDated is a string
if (isDated == true){
    console.log("passed");
}

Why does this happend? Which is the best way to avoid this?


EDIT:

I've found a blog that has a solution to avoid this problem: http://www.peterbe.com/plog/data-and-attr-in-jquery

Below a prototype method called .toBoolean() to validate true/false when it comes as a string based on some responses from this post:

String.prototype.toBoolean = function ()
{
    var dictionary = { "True": true, "False": false };
    return dictionary[this];
};

Boolean.prototype.toBoolean = function () {
    return this;
};

Number.prototype.toBoolean = function ()
{
    if (this) {
        return true;
    }

    return false;
};
1
  • Leo: Please refrain from making minor/ superfluous edits to your question. Commented Sep 18, 2015 at 7:57

1 Answer 1

10

If you want to know why C# outputs True and False instead of the lowercase versions, see this question.

If you want to know why it's not converted to a boolean value, it's because all <input> elements' values are considered text by JavaScript. It's up to you to convert it into another type. With checkboxes/radio buttons that's already done by using the .checked attribute (for jQuery, either $('.someClass').is(':checked') or $('.someClass').prop('checked') will work). Otherwise, the best way would be comparing the value to a string, and using that, for example: if ($('.someClass').val().toLowerCase() === 'true').

Sign up to request clarification or add additional context in comments.

2 Comments

great answer. var isDated = ($('.someClass').val().toLowerCase()=== "true"); would be the ideal converter
or this var isDated = {"True": true, "False": false}[$('.someClass').val()];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.