Reputation: 5591
So, I have following list:
<li><a class="name" title="<?php echo $names;?></a></li>
And let say, you get the following names: Steve, Mike, Sean, Ryan
.
Now, I have the following js:
var names= [];
function GET_NAMES ()
{
//Something
}
So, when the GET_NAMES()
function is loaded, I want to collect all the values in the title
in the list
and put in the var names=[]
How do I collect the values into variable?
Upvotes: 3
Views: 62
Reputation: 3883
Using jQuery, you will first need to select the <a>
elements, and then you can get the title attributes for each.
$("li a").each(function(){
names.push($(this).attr('title')); // this will get the title and push it onto the array.
}
Upvotes: 2
Reputation: 24638
I would suggest using the jQuery .map()
method and, you can also use a data-
attribute to hold the names
. However if you elect to use the title
attribute then you would just need to replace $(this).data('title')
with this.title
in the code below:
var names = $('.name').map(function() {
return $(this).data('title');
})
.get();
var names = $('.name').map(function() {
return $(this).data('title');
})
.get();
console.log( names );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li><a class="name" data-title="Steve">Steve</a></li>
<li><a class="name" data-title="Mike">Mike</a></li>
<li><a class="name" data-title="Sean">Sean</a></li>
<li><a class="name" data-title="Ryan">Ryan</a></li>
</ul>
Upvotes: 1
Reputation: 15555
var names=[]
$('li a').each(function() {
names.push($(this).attr('title'))
})
console.log(names)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<a class="name" title="Steve"></a>
</li>
<li>
<a class="name" title="Steve1"></a>
</li>
<li>
<a class="name" title="Steve2"></a>
</li>
<li>
<a class="name" title="Steve3"></a>
</li>
</ul>
Try this way
Upvotes: 2