I'm using the jQuery Quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice.
How do I get the data-id attribute? I'm using the .on()
method to re-bind the click event for sorted items.
$("#list li").on('click', function() { // ret = DetailsView.GetProject($(this).attr("#data-id"), OnComplete, OnTimeOut, OnError); alert($(this).attr("#data-id")); });
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <ul id="list" class="grid"> <li data-id="id-40" class="win"> <a id="ctl00_cphBody_ListView1_ctrl0_SelectButton" class="project" href="#"> <img src="themes/clean/images/win.jpg" class="project-image" alt="get data-id" /> </a> </li> </ul>
The id attribute specifies a unique id for an HTML element. The value of the id attribute must be unique within the HTML document. The id attribute is used to point to a specific style declaration in a style sheet. It is also used by JavaScript to access and manipulate the element with the specific id.
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
The id attribute assigns an identifier to the <data> element. The id allows JavaScript to easily access the <data> element. It is also used to point to a specific id selector in a style sheet. Note: Not all browsers support the <data> element.
To get the contents of the attribute data-id
(like in <a data-id="123">link</a>
) you have to use
$(this).attr("data-id") // will return the string "123"
or .data()
(if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the number 123
and the part after data-
must be lowercase, e.g. data-idNum
will not work, but data-idnum
will.
If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:
Through JavaScript
<div id='strawberry-plant' data-fruit='12'></div> <script> // 'Getting' data-attributes using getAttribute var plant = document.getElementById('strawberry-plant'); var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12' // 'Setting' data-attributes using setAttribute plant.setAttribute('data-fruit','7'); // Pesky birds </script>
Through jQuery
// Fetching data var fruitCount = $(this).data('fruit'); OR // If you updated the value, you will need to use below code to fetch new value // otherwise above gives the old value which is intially set. // And also above does not work in ***Firefox***, so use below code to fetch value var fruitCount = $(this).attr('data-fruit'); // Assigning data $(this).attr('data-fruit','7');
Read this documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With