How to get the value of data attribute using jquery - javascript

I am working on a node.js application which generates a html page. This html page displays a list of associates built according to the data passed onto this page. A list is built something like as follows:
<ul class="notification-body" style="">
//loop for all assocaite id's passed to this page
<li class="testClass" data-associateid="<%= assocID %>">
<span>
<span class="subject">
<label class="btnClass label label-info">ClickMe!</label>
</span>
</span>
</li>
The generated html src looks something like this:
<ul class="notification-body" style="">
<li class="testClass" data-associateid="AA01">
<li class="testClass" data-associateid="AA02">
<li class="testClass" data-associateid="AA03">
I am trying to get the value of the data attribute using Jquery & I tried the following:
$(".btnClass").click(function(){
console.log($".testClass").attr("data-associateid"));
});
But this outputs'AA01'everytime i click on the btn and I am not getting the expected output in the console:
AA01
AA02
AA03
I tried the following also but it gives me undefined:
$(".btnClass").click(function(){
console.log($(this).find(".testClass").attr("data-associateid"));
});

You need to use jQuery.data().
I've created a jsFiddle to show this working.
I've closed the LI because AR.
<ul class="notification-body" style="">
<li class="testClass" data-associateid="AA01">1</li>
<li class="testClass" data-associateid="AA02">2</li>
<li class="testClass" data-associateid="AA03">3</li>
</ul>
Here's the JavaScript:
$(document).ready(function() {
$('.testClass').on('click', function(){
alert( $(this).data('associateid') );
});
});
Anytime you have an attribute that starts with data-, you can reference the string after the dash as a data container. Here, I'm calling jQuery.data() on an object (the LI) and asking for the data in the container associateID.

What you are currently doing:
$(".btnClass").click(function(){
console.log($(".testClass").attr("data-associateid"));
});
Will match the first instance of .testClass and print the data-associateid attribute. What you seem to want to do is to iterate over all .testClass and print their data-associateid values:
$(".btnClass").click(function(){
$(".testClass").each(function() {
console.log($(this).attr('data-associateid'));
});
});
Based on your updated HTML you would do this:
$(".btnClass").click(function() {
var id = $(this).parents('.testClass').attr('data-associateid');
console.log(id);
});
This will search the parents of the clicked on .btnClass to find elements with the class .testClass.

To get the data for that instance you simply need to traverse to the parent <li>.
Within an event handler, this is the element that the event occured on. Use closest() to access the parent <li>
$(".btnClass").on('click', function(){
alert( $(this).closest('li').data('associateid') );
});

Assign different classes to your li elements like this:
<ul class="notification-body" style="">
<li class="testClass1" data-associateid="AA01">test 1</li>
<li class="testClass2" data-associateid="AA02">test 2</li>
<li class="testClass3" data-associateid="AA03">test 2</li>
</ul>
Note, that I closed your li and ul tags to have valid HTML.
And then you can select an element with its own class:
console.log($(".testClass2").attr("data-associateid"));
I created a JSFiddle for you:
http://jsfiddle.net/8rLpbk5m/

I had hoped you could do it with just a find but apparently not. You have to use each to loop through all the elements.
$(".btnClass").click(function(){
$(".testClass").each(function() {
console.log($(this).attr('data-associateid'));
});
});
View it here: http://jsfiddle.net/rt677qp5/

Using .data() is more logical in this case.
$(".btnClass").click(function() {
$(".testClass").each(function() {
alert($(this).data("associateid"));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="notification-body" style="">
<li class="testClass" data-associateid="AA01"></li>
<li class="testClass" data-associateid="AA02"></li>
<li class="testClass" data-associateid="AA03"></li>
</ul>
<button class="btnClass"></button>

Related

Get <li> value based on class

I have the following example code:
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
When a specific <li> is selected, the class changes to whatever the name is, plus sortUp or sortDown.
Example:
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
I am trying to get the value of the actual text inside the <li>, but I keep getting undefined.
var li = document.getElementById('TEST');
alert($('#TEST').filter('.sort').html());
I tried using different ways but no matter what I do I can't get the actual value, which in this case should be 222.
Any idea what I am doing wrong?
You can select the li with either sortUp or sortDown by using the [attribute*="value"] selector,
The [attribute*="value"] selector is used to select elements whose
attribute value contains a specified value.
const li = document.querySelector('[class*="sort"]');
console.log(li.textContent);
li.style.background = "red";
<ul class="name_of_class" id="TEST">
<li class="foo">111</li>
<li class="boo sortDown">222</li>
<li class="goo">333</li>
<ul>
See css attribute selectors
I'm not sure what the classes have to do with your requirement to get the text of the clicked li element. Just set up a click event handler on the ul and then in the handler, check the event target to ensure it was an li, then just get the text of the event target.
document.getElementById("TEST").addEventListener("click", function(evt){
if(evt.target.nodeName==="LI"){
alert(evt.target.textContent);
}
});
<ul class="name_of_class" id="TEST">
<li class="foo">1</li>
<li class="boo">2</li>
<li class="goo">3</li>
<ul>
Maybe you can try this:
alert($('#TEST').find('li[class^='sort']').html());
You will find a li element that has a class that starts with "sort".
You can see more of this selector here.

How to get the string in div onclick attribute with jQuery?

I have a banner which is something like this:
<ul id="carousel">
<li id="item1">
<div onclick="window.open('mylinkhere.com,'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
</div>
</li>
<li id="item2">
<div onclick="window.open('myotherlinkhere.com,'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
</div>
</li>
</ul>
I need to access the links written in onclick attribute i.e. mylinkhere.com
I tried
var banners = $($("#carousel")[0]).children().filter("li");
var b_items = $(banners[0]).children().filter("div");
attr_val = $(".b_items")[0].attr("onclick");
But i couldn't. By the way i don't know from the start that which item will be in the carousel because it's randomized by another function. So i cannot access them with item1 item2 ect.
Thanks.
You can set the url in a data attribute and read easily like this:
<ul id="carousel">
<li id="item1">
<div data-url="mylinkhere.com" onclick="window.open($(this).data('url'),'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
</div>
</li>
<li id="item2">
<div data-url="myotherlinkhere.com" onclick="window.open($(this).data('url'),'_blank')" style="cursor:pointer;margin-left:-436px;width:996px;height:100%">
</div>
</li>
</ul>
To read:
var b_items = $(banners[0]).children().filter("div");
var link = $(b_items).data('url');
See this fiddle:
http://jsfiddle.net/Pontual/pugytfwu/
For me, the following code works as expected (Chrome 44, jQuery 2.1.3):
var s = jQuery('#carousel li div');
s.each(function(i,node) {
alert(jQuery(node).attr('onclick'));
});
http://jsfiddle.net/aavf1450/
Possible problem is that in your code, you do not wrap the element into $(...), so .attr() is not a valid function, as using indexers on a jQuery object returns raw HTML elements.

Get value from list item on ol list click function

I need to get value form every list click
Here is my list:
<c:forEach items="${cmlist}" var="records">
<ol class="dd-list" id="chapterlist" >
<li id="cs" class="dd-item" data-id="1" value="${records.levelID}">
<div class="dd-handle">
Chapter: ${records.levelName}
</div>
</li>
</ol>
</c:foreach>
here is my click function code:
$(window).load(function(){
$("#chapterlist li a").on("click", function(){
level = $(this).parent('li').val();
console.log("level"+level);
});
});
Could you please help?
parent() function only goes up one level of DOM, so it gets to your <div> element and stops there. Use parents() instead.
JSFiddle
Note, that val() will only work if value is an integer. Shouldn't be a problem with an ordered list, though, where value is the number of an item.
You cannot use the value method to get the value attribute of this object.
Please, update your jsp by
<c:forEach items="${cmlist}" var="records">
<ol class="dd-list" id="chapterlist" >
<li id="cs" class="dd-item" data-id="1" data-value="${records.levelID}"><div class="dd-handle">Chapter: ${records.levelName} </div>
</li></ol></c:foreach>
And your javascript by
level = $(this).parent('li').data('value');
Fiddle to test this solution

How to find the nearest parent element attribute value using Jquery

I am facing a problem on getting the nearest parent element attribute value using Jquery. Can anyone help me on this. My element structure is as below,
<ul class="Someclass">
<li><span id=3 class="heading"></span>
<ul>
<li>
<ul> <li><span ><button onclick= "redirect()"></button></span</li>
<ul>
</li>
</ul>
</li>
<ul>
<script type="text/javascript">
function redirect() {
alert(....)
}
</script>
In the above code when i click that element having onclick event i want to get the value as 3 in alert() which is in the element having the class heading. The above code is in for loop so it will have more code like this in a same page.
Give this Try
function redirect(elem) {
alert($(elem).closest('.Someclass > li').children('span').attr('id'))
}
Change Markup to this:
<li><span><button onclick= "redirect(this)"></button></span</li>
this will reffer to the current object in DOM
By wrapping elem in $(elem) will convert it to jQuery object then you can traverse to the closest and find span
You can also filter that span with .children('span:first')
Fiddle Example
With your current code, pass the clicked element reference to the function like
<button onclick= "redirect(this)">asdf</button>
then
function redirect(el) {
alert($(el).closest('.Someclass > li').children('span').attr('id'))
}
Demo: Fiddle
Bu a more recommended way will be is to use jQuery event handlers like
<button class="redirect">asdf</button>
then
jQuery(function($){
$('.Someclass .redirect').click(function(){
alert($(this).closest('.Someclass > li').children('span').attr('id'))
})
})
Demo: Fiddle
This should do it.
alert($(this).closest('.heading').attr('id'));
$(".someclass li").click(function(){
$(this).closet('.heading').attr('id');
})
could you pass it on as a parameter to your redirect function? You'd somehow hold that value in a variable in your loop.
I got a solution if you can change the id and class to parent li
Working Demo
More about parent selector
Jquery
function redirect(elem) {
var myid = $(elem).parents(".heading").attr("id");
alert(myid);
}
HTML
<ul class="Someclass">
<li id="3" class="heading">
<ul>
<li>
<ul> <li><span ><button onclick="redirect(this)" id="haha">Go</button></span</li>
<ul>
</li>
</ul>
</li>
<ul>

Weird behavior with .parents() and .closest() when trying to return parent <ul> element id in jQuery

So I've got 2 <ul> containers each with id's. Inside of them are a list of <li> elements.
The first <ul> is <ul id="coaches-list">. The second is <ul id="players-list">.
There are tags within each <li> that have an id called close (which is a link that I'm using as my selector), which will delete each <li> node once clicked. I'm trying to target each <ul> container to see where it is coming from.
My HTML is:
<!-- coaches box -->
<div class="box">
<div class="heading">
<h3 id="coaches-heading">Coaches</h3>
<a id="coaches" class="filter-align-right">clear all</a>
</div>
<ul id="coaches-list" class="list">
<li><span>Hue Jackson<a class="close"></a></span></li>
<li class="red"><span>Steve Mariuchi<a class="close"></a> </span></li>
</ul>
</div>
<!-- players box -->
<div class="box">
<div class="heading">
<h3 id="players-heading">Players</h3>
<a id="players" class="filter-align-right">clear all</a>
</div>
<ul id="players-list" class="list">
<li><span>Steve Young<a class="close"></a></span></li>
<li><span>Gary Plummer<a class="close"></a></span></li>
<li><span>Jerry Rice<a class="close"></a></span></li>
</ul>
</div>
My remove tag function in jQuery is:
function removeSingleTag() {
$(".close").click(function() {
var $currentId = $(".close").closest("ul").attr("id");
alert($currentId);
// find the closest li element and remove it
$(this).closest("li").fadeOut("normal", function() {
$(this).remove();
return;
});
});
}
Whenever I click on each specific tag, it's removing the proper one I clicked on, although when I'm alerting $currentId, if I have:
var $currentId = $(".close").closest("ul").attr("id");
It alerts 'coaches-list' when I'm clicking on a close selector in both <ul id="coaches-list" class="list"></ul> and <ul id="players-list" class="list"></ul>
If I change that to:
var $currentId = $(".close").parents("ul").attr("id");
It has the same behavior as above, but alerts 'players-list', instead.
So when using closest(), it's returning the very first <ul> id, but when using parents(), it's returning the very last <ul> id.
Anyone know what is going on with this whacky behavior?
It's expected behavior.
You should use:
var $currentId = $(this).closest("ul").attr("id");
$(this) points at the clicked .close.
$(".close") points at the first one found.
It's because you run that selector from click handler you should use this instead:
var $currentId = $(this).closest("ul").attr("id");
Try using this function to get the parent:
var $currentId = $(this).parents().first();
I've never used the .closest() function but according to jQuery what you have specified should work. Either way, try that out and tell me how it goes.
You also need to make it so that it selects the current element by using $(this)

Categories