Retrieve boolean data from data attribute in jquery

jquery get data attribute value
jquery update data attribute
html data attribute jquery
jquery data selector
jquery add data attribute
javascript get data attribute
jquery has data attribute
jquery get all data attributes

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/

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/

.data(), To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ). The jQuery .data() method is smart about recognizing boolean and numeric values and converts them into their native type. So $('#test').data('return'); returns the boolean true, not "true". If you want to get the raw data (without the automatic data conversion), you can use .attr(): $('#test').attr("data-return");

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.

jQuery.data(), Store arbitrary data associated with the specified element and/or return the value Regarding HTML5 data-* attributes: This low-level method does NOT retrieve  Try using .prop to deal with boolean that is for supported attributes like selected/disabled/checked e.t.c $('#element').prop('attribute', true); from jQuery docs, (an example)

"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/

jQuery.hasData(), jQuery.hasData( element )Returns: Boolean. Description: Determine whether an element has any jQuery data associated with it. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Retrieving HTML data-attributes using jQuery. Ask

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>

.attr(), Using jQuery's .attr() method to get the value of an element's attribute has two main benefits: Concerning boolean attributes, consider a DOM element defined by the To safely set values on DOM objects without memory leaks, use .data() . An element's data-* attributes are retrieved the first time the data() method is invoked upon it, and then are no longer accessed or mutated (all values are stored internally by jQuery). Every attempt is made to convert the attribute's string value to a JavaScript value (this includes booleans, numbers, objects, arrays, and null).

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"));

.prop(), Get the value of a property for the first element in the set of matched elements or set one According to the W3C forms specification, the checked attribute is a boolean To safely set values on DOM objects without memory leaks, use .data​() . According to the W3C forms specification, the checked attribute is a boolean attribute, which means the corresponding property is true if the attribute is present at all—even if, for example, the attribute has no value or is set to empty string value or even "false". This is true of all boolean attributes.

How You Can Use HTML5 Custom Data Attributes and Why, Gajendar Singh walks you through HTML5 custom data attributes, why This makes it harder to parse the data in JavaScript to actually get jQuery only retrieves the value of data attributes the first time they are accessed. jQuery data() is stored in a separate object inside the object’s internal data cache in order to avoid key collisions between internal data and user-defined data.

How to Use HTML5 Data Attributes, Today we look at how to use HTML5 data attributes. Every browser will let you fetch and modify data- attributes using the getAttribute and Since version 1.4.3, jQuery's data() method has parsed HTML5 data attributes. Notice that alt attribute value is updated using our jQuery set attribute code. Attributes are the basic components of the html elements helps to manipulate in jQuery. You can change the attributes in the way you want once you get access to those properties.

Boolean, The Boolean object is an object wrapper for a boolean value. Note: When the non-standard property document.all is used as an argument for this constructor, the result is a Boolean object with Update compatibility data on GitHub Get the latest and greatest from MDN delivered straight to your inbox. For instance, in retrieving an element, I can retrieve the value of data attributes on it without using the "data-" prefix: I just pass the name of the data attribute to the jQuery data function. This example retrieves the value of the data-salary attribute for employee B456, assuming that the data-empid attribute is still in place:

Comments
  • Be sure your "true" and "false" attribute values are lower case for this to work correctly.
  • is there a way to make it case insensitive, for MVC compatability?
  • @TomerW - No. .data() and .attr() and even the DOM function .getAttribute() are all case sensitive.
  • 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.
  • @TomerW There is a way of using it nicely in ASP.MVC. if you pass your value to Json.Encode (msdn.microsoft.com/en-us/library/…) in your view it'll generate a lower case true/false and it'll work fine. Example: <input type=checkbox data-toplevel="@Json.Encode(Model.TopLevel)"/>
  • 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
  • The link to the fiddle didn't open the code here. Could you take a look ?
  • 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.