Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting values into variable

Tags:

jquery

php

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?

like image 682
Steve Kim Avatar asked Mar 21 '26 05:03

Steve Kim


2 Answers

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

like image 52
guradio Avatar answered Mar 23 '26 18:03

guradio


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.
}
like image 39
Jordan Soltman Avatar answered Mar 23 '26 20:03

Jordan Soltman