Setting bool value to input and getting string type via javascript/jquery
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')
.
Leo
O Captain! my Captain! our fearful trip is done; The ship has weathered every rack, the prize we sought is won; The port is near, the bells I hear, the people all exulting, While follow eyes the steady keel, the vessel grim and daring: But O heart! heart! heart! O the bleeding drops of red, Where on the deck my Captain lies, Fallen cold and dead. O Captain! my Captain! rise up and hear the bells; Rise up—for you the flag is flung—for you the bugle trills; For you bouquets and ribboned wreaths—for you the shores a-crowding; For you they call, the swaying mass, their eager faces turning; Here Captain! dear father! This arm beneath your head; It is some dream that on the deck, You’ve fallen cold and dead. My Captain does not answer, his lips are pale and still; My father does not feel my arm, he has no pulse nor will; The ship is anchored safe and sound, its voyage closed and done; From fearful trip, the victor ship, comes in with object won; Exult, O shores, and ring, O bells! But I, with mournful tread, Walk the deck my Captain lies, Fallen cold and dead.
Updated on July 24, 2022Comments
-
Leo almost 2 years
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; };
-
naveen over 8 yearsgreat answer.
var isDated = ($('.someClass').val().toLowerCase()=== "true");
would be the ideal converter -
Salman A over 8 yearsor this
var isDated = {"True": true, "False": false}[$('.someClass').val()];