Reputation: 35
I'm trying to push data from this h5 tag to my favorites array but it keeps returning undefined. It does return something, and it works on the click, but it just keeps returning undefined.
<h5 id="favoriteartist"> Armin van Buuren </h5>
And here's my script.
$('#favoriteadd').live('click',function() {
var favorites = []
favorites.push( $('h5 #favoriteartist').val() );
console.log(favorites);
});
What am I doing wrong here?
Upvotes: 0
Views: 15025
Reputation: 47099
Your selector is wrong. Simple use:
$("#favoriteartist");
And also you should use .text
not .val
:
favorites.push( $("#favoriteartist").text() );
And if you are using jQuery 1.7+ you should use .on
not .live
:
$(document).on('click', '#favoriteadd', function() {
var favorites = []
favorites.push( $('#favoriteartist').text() );
console.log(favorites);
});
Now you can change document
with a static selector. If #favoriteadd
is in the docuement when the event is bound you can simple bind it as a normal event:
$('#favoriteadd').on('click', function() {
var favorites = []
favorites.push( $('#favoriteartist').text() );
console.log(favorites);
});
h5 #favoriteartist
is like saying:
favoriteartist
witch is a (grand-)child of these h5.We know that an id in html is always unique, so we simple say:
favoriteartist
.Upvotes: 7
Reputation: 21742
Your code does not return undefined. It returns an array with one element. The element is undefined
meaning your selector is selecting an h5
element that does not have a value and val() of that selection therefor returns undefined. .val()
can be used on eg. an text input field to get the value the user have typed in
<input type="text" id="t" value="..." />
...
$("#t").val(); //will return the value of the input element
in the case of a h5 element if you wish to get the textual content of that element use .text()
instead.
$("#favoriteartist").text(); //will return " Armin van Buuren "
Upvotes: 0