Newbie
Newbie

Reputation: 23

Jquery What am I doing wrong?

i want to read out the value of List item and write it into span.
So that the lists looks like this:

But i dont find the error:

<div id="Listgroup">
    <ul id="list1"> 
      <li><a href="" value="1">my first item<span></span></a></li>
      <li><a href="" value="2">another item<span></span></a></li>
      <li><a href="" value="3">next item<span></span></a></li>
    </ul>
<br>
    <ul id="list2"> 
      <li><a href="" value="a">my first item<span></span></a></li>
      <li><a href="" value="b">another item<span></span></a></li>
      <li><a href="" value="c">next item<span></span></a></li>
    </ul>
</div>

<script>
$(function(){
$("li a").each(function(idx, item){
    $("span", "li a[value|=' + $(this).attr('value') + ']")
        .html(" (" + $(this).attr('value') + ")");
});
});
</script>

please help

Thank you

Upvotes: 0

Views: 70

Answers (1)

Curtis
Curtis

Reputation: 103428

Your quotation marks don't match the string quotation marks, so its classing ' + $(this).attr('value') + ' as a string, rather than $(this).attr('value') as an object

$("span", "li a[value|=" + $(this).attr('value') + "]")

Also, you don't need to find the value like that. You already know what this is, so you can just find the span from there.

Furthermore, the anchor element has no value attribute, making this HTML invalid. You should change it to data-value which would make it compliant with HTML5:

$(function(){
$("li a").each(function(idx, item){        
    $(this).find("span").html(" (" + $(this).data("value") + ") ");    
});
});

-- SEE DEMO --

Upvotes: 3

Related Questions