Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a HTML data value as a string with jQuery?

I have the following in my source HTML:

<li><a href="#" data-value="01">Test</a></li> 

I want to get the value of the data attribute so I am using the following:

var abc = $(this).data('value'); 

This works okay BUT not if there is a leading zero. For example the above placed the value "1" into abc.

Is there a way that I can get it not to convert the "01" into "1" ?

like image 649
Samantha J T Star Avatar asked Apr 04 '12 16:04

Samantha J T Star


People also ask

How show data from HTML using jQuery?

click(function() { $("#ask_user"). hide(); $. ajax({ type: "post", url: '/nearest_banks/radius', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $("#allowed"). show(); var str = ""; $("#places").

Which method converts a given value into a string in jQuery?

The String() method converts a value to a string.


1 Answers

this.dataset.value;  // Or old school this.getAttribute('data-value'); 

const a = document.querySelector("a");  console.log('Using getAttribute, old school: ', a.getAttribute('data-value'));  console.log('Using dataset, conforms to data attributes: ', a.dataset.value);
<ul>    <li><a href="#" data-value="01">Test</a></li>  </ul>

Thanks to @MaksymMelnyk for the heads up on dataset

like image 60
Juan Mendes Avatar answered Sep 20 '22 20:09

Juan Mendes