0

I have an asp.net webform with a textbox. The value of the textbox is "False" and has been verified by viewing the page source in the browser.

Despite being set to false the following code results in beginDateReqd being set to false and consequently, DateParms being displayed when it shouldn't be.

var beginDateReqd = Boolean($('.HiddenBeginDateTimeRequired').val());
if (beginDateReqd) {
    $('.DateParms').show();
}

What am I doing wrong? Thanks!

DenaliHardtail
  • 27,362
  • 56
  • 154
  • 233
  • Please check this existing question for more details. http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript – Saurabh Sharma Nov 15 '11 at 19:38

5 Answers5

2

Safer would be first to convert value "toLowerCase" and then compare with "true" value:

var beginDateReqd = ($('.HiddenBeginDateTimeRequired').val().toLowerCase() == "true");
if (beginDateReqd) {
    $('.DateParms').show();
}
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
1

Why not just use a comparison operator?

var beginDateReqd = ($('.HiddenBeginDateTimeRequired').val() == "True");
if (beginDateReqd) {
    $('.DateParms').show();
}
Polynomial
  • 27,674
  • 12
  • 80
  • 107
1
    var beginDateReqd = parseBoolean ($('.HiddenBeginDateTimeRequired').val());
    if ( beginDateReqd  ) {
        $('.DateParms').show();
    }



function parseBoolean(str) {
  return /^true$/i.test(str);
}
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Pardon my nitpick, but I'd either rename that function `isTrue()` or throw an error if the value is not either `true` or `false`. – gilly3 Nov 15 '11 at 19:31
  • Using regex for this is like going after a fly with a tactical nuclear strike... what's wrong with just `foo == "True"`? – Polynomial Nov 15 '11 at 19:32
  • @Polynomial - Do regular expressions perform worse than string comparison? Can you point me to an article on the subject? Personally, I like them - they are so much more precise and meaningful than doing eg `mystring.toLowerCase() == somestring`. – gilly3 Nov 15 '11 at 19:38
0

The Boolean object does not parse string values for truthiness. You should be using a comparison operator or a regex test. See http://www.w3schools.com/js/js_obj_boolean.asp

Ben
  • 10,056
  • 5
  • 41
  • 42
0

Use comparison after making sure of the case

var beginDateReqd = ($('.HiddenBeginDateTimeRequired').val().toLowerCase() == "true");
amit_g
  • 30,880
  • 8
  • 61
  • 118