0

Here is jquery code in rails app. The purpose of the code is to eval the value of #rfq_need_report and show the #rfq_report_language if need_report is true or hide if false:

$(document).ready(function() {
  var rpt = $('#rfq_need_report').val();
  alert(rpt);
  if (rpt) {
     alert(rpt);
    $('#rfq_report_language').show();
    alert('show');      
  } else {
    $('#rfq_report_language').hide();
    alert(rpt);
    alert('hide');
  }
}); // end ready

The alert here is just for debug. The rpt is false, however alert('show') gets executed. It seems that the if loop is taking false and decided to execute the loop for true. Sometime If loop is working and sometime it does not. What could cause this strange behavior? Thanks.

user938363
  • 9,990
  • 38
  • 137
  • 303
  • maybe rpt is just whitespace so it looks empty? '' will evaluate to false, ' ' will evaluate to true – yas Jan 26 '12 at 18:10
  • Instead of working with alert(..) in javascript you should consider using the console if your browser supports it or if you can download an extension to have a console. A simple console.log(value) would show you if it's a string or a boolean and its value. It is far better than debugging with calls to alert(...) –  Jan 26 '12 at 18:18

3 Answers3

2

In HTML the value field of any input like value="something" is always evaluated as a string. My guess is that in javascript you either set that value to true or false but it is in fact set as "true" or "false" as strings. You could try what was answered on this topic : How can I convert a string to boolean in JavaScript?

Community
  • 1
  • 1
1

rpt could be a string, therefore converting it into a boolean will help:

if(rpt === "false") { rpt = false; } else { rpt = true; }
Gregor
  • 4,306
  • 1
  • 22
  • 37
1

I have to assume that $('#rfq_need_report').val() is not passing back an actual boolean value, but something that JavaScript considers 'truthy', which is why your if statement executes the truth clause.

There are two quick methods (that I use) to convert 'truthy' values to an actual boolean:

1: var bool = !!truthy;

2: var bool = truthy === 'true'

I use the second when expecting a string value, and the first when not expecting a string.

The first example may need an explanation, so...

The first ! "nots" the truthy value to an actual boolean, albeit the opposite of what I wanted, the second "nots" it right back to where it should be.

For more examples of truthy vs falsy, simply pop javascript truthy falsy into your favorite search engine and start reading. My personal quick reference is: Truthy and falsy in JavaScript

pete
  • 24,141
  • 4
  • 37
  • 51