71

I am trying to retrieve a data attribute of type Boolean from an html DIV element , however it is always returning false when the string is converted to boolean .

HTML

<div id='test' data-return="true"></div>

JS

isreturn_str = $('#test').data('return');
isreturn = (isreturn_str === 'true');
if (isreturn) {
    document.write("It is true");
} else {
    document.write("It is false");
}

output

It is false

http://jsfiddle.net/neilghosh/494wC/

CyclingFreak
  • 1,614
  • 2
  • 21
  • 40
Neil
  • 5,919
  • 15
  • 58
  • 85

6 Answers6

127

The jQuery .data() method is smart about recognizing boolean and numeric values and converts them into their native type. So this returns the boolean true, not "true":

$('#test').data('return');

If you want to get the raw data (without the automatic data conversion), you can use .attr():

$('#test').attr("data-return");

See the working test case here: http://jsfiddle.net/jfriend00/6BA8t/

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • 13
    Be sure your "true" and "false" attribute values are lower case for this to work correctly. – Blake Mitchell Dec 06 '13 at 21:43
  • 2
    is there a way to make it case insensitive, for MVC compatability? – Tomer W Mar 01 '14 at 19:29
  • 1
    @TomerW - No. `.data()` and `.attr()` and even the DOM function `.getAttribute()` are all case sensitive. – jfriend00 Mar 01 '14 at 19:41
  • 2
    Thanks using the .data() method was exactly what I needed to return a boolean from a data-attribute. I was struggling using .attr() incorrectly until now. – Rich Finelli Jun 05 '15 at 14:30
  • @TomerW There is a way of using it nicely in ASP.MVC. if you pass your value to Json.Encode (https://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode(v=vs.111).aspx) in your view it'll generate a lower case true/false and it'll work fine. Example: `` – chipples Nov 28 '16 at 13:09
6

jQuery recognizes the string "true" as it's boolean counterpart (in the context of data attributes) and thus:

typeof isreturn_str; // boolean

but you're strictly comparing to the string 'true' which yields false as a string is not a boolean.

Yoshi
  • 54,081
  • 14
  • 89
  • 103
  • That's what I did and got the error, which made me come to this page. There is a serious disadvantage of using data() for long values. If Javascript automatically converts the value to numeric type, then a few trailing digits might be lost depending upon the number's size – Ridhuvarshan Jun 11 '18 at 10:26
4

In my case the proposed solutions did not helped me therefore I created my own boolean conversion function using jquery:

/**
* Convert a value into a boolean
* @param {Mixed} value The value to check convert into boolean
* @return {Boolean}
*/
var boolVal=function(value){
  var falseValues=['false',0,undefined,'0','no','null',null];

  if (typeof value === 'string' || value instanceof String){
      value=value.toLowerCase();
  }

  return $.inArray(value, falseValues) == -1
}

So I retrieve the value via attr jquery method and I pass it like that for example:

boolVal($(href).attr('data-sidebar-sm-display'));

Also you can see it for youself in the following demo:

var boolVal = function(value) {
  var falseValues = ['false', 0, undefined, '0', 'no', 'null', null];

  if (typeof value === 'string' || value instanceof String) {
    value = value.toLowerCase();
  }

  return $.inArray(value, falseValues) == -1
}

console.log("#1_true: " + boolVal($("#1_true").attr('data-boolean')))
console.log("#2_true: " + boolVal($("#2_true").attr('data-boolean')))
console.log("#3_true: " + boolVal($("#3_true").attr('data-boolean')))
console.log("#4_true: " + boolVal($("#4_true").attr('data-boolean')))
console.log("#5_true: " + boolVal($("#5_true").attr('data-boolean')))
console.log("#6_true: " + boolVal($("#6_true").attr('data-boolean')))
console.log("#7_true: " + boolVal($("#7_true").attr('data-boolean')))

console.log("#1: " + boolVal($("#1").attr('data-boolean')))
console.log("#2: " + boolVal($("#2").attr('data-boolean')))
console.log("#3: " + boolVal($("#3").attr('data-boolean')))
console.log("#4: " + boolVal($("#4").attr('data-boolean')))
console.log("#4: " + boolVal($("#no_data").attr('data-boolean')))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="1" data-boolean="false"></div>
<div id="2" data-boolean="0"></div>
<div id="3" data-boolean="null"></div>
<div id="no_data"></div>
<div id="4" data-boolean=false></div>

<div id="1_true" data-boolean=yes></div>
<div id="2_true" data-boolean="yes"></div>
<div id="3_true" data-boolean="true"></div>
<div id="4_true" data-boolean="1"></div>
<div id="5_true" data-boolean=1></div>
<div id="6_true" data-boolean="true"></div>
<div id="7_true" data-boolean="TRUE"></div>

The basic idea it to define what data-attribute is considered by logic "false" and anything else is set as true.

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
2

"true" is internally casted to boolean (try alert (typeof(isreturn_str))), hence your === comparison fails on type check.

You could call .toString()

isreturn_str = $('#test').data('return').toString();

http://jsfiddle.net/494wC/8/

Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
1

This doesn't answer your question exactly, but if you're able to change the design of the HTML, consider making the attribute's presence the boolean value, instead of converting string values. In other words, have <div id="test" data-isreturn> represent true, and just <div id="test"> (without the attribute) represent false.

While this may seem less intuitive for some coders, it's actually semantically consistent with HTML (e.g. the disabled attribute), and it eliminates concerns about typos and capitalisation in strings. It reduces ambiguity, and is terse and elegant.

jQuery's .prop() function is helpful for this.

Michael Scheper
  • 6,514
  • 7
  • 63
  • 76
-6

I'm using jquery 2.1.0 and I have to use eval

// $('#test').attr("data-return");" doesn't works
eval($('#test').attr("data-return"));
Javier Gutierrez
  • 549
  • 5
  • 16
  • 1
    Avoid EVAL at all costs. It's not needed in most cases, and is usually a sign of bad code / a XSS vulnerability if any data comes from a db. Just don't use eval. – Richard Duerr Aug 14 '18 at 21:07
  • Here's more info for why `eval` should be avoided, and why this answer is so heavily down-voted. This page the third hit for the websearch I just did for 'JavaScript eval', which shows how widely held an opinion this is. https://www.digitalocean.com/community/tutorials/js-eval – Michael Scheper Jun 18 '21 at 14:07