Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

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

if(rpt === "false") { rpt = false; } else { rpt = true; }

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top