Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get `data-value` using jQuery?

How can I get data-value country using jQuery? I need this in variable:

var country = ...;

HTML:

<a id="obj-details" data-value="{city:'berlin', street: 'mozart', postal_code: '55555', country: 'DE'}">test</a>
like image 669
user3266909 Avatar asked Jul 04 '14 08:07

user3266909


People also ask

How get data attribute value in jQuery?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How do you find the element of data value?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

How do I find data attributes?

To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.

How can get li id value in jQuery?

ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });


1 Answers

To read data-value attribute use below jQuery :

$("#obj-details").data('value');

and to read country from the data-value use below jQuery :

 var value = $("#obj-details").data('value');
 var obj = eval('(' +value + ')');

 var country = obj.country;
 alert(country );

Demo

like image 133
Bhushan Kawadkar Avatar answered Sep 26 '22 10:09

Bhushan Kawadkar