0

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?

0

2 Answers 2

7

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:

  1. Give me all h5 elements on the whole page.
  2. Now give me all elements with the id favoriteartist witch is a (grand-)child of these h5.

We know that an id in html is always unique, so we simple say:

  1. Give me the element with the id favoriteartist.
Sign up to request clarification or add additional context in comments.

9 Comments

and add the ; in second line and not use console.log in IE etc.
@bart why not use console.log in IE?
@NULL we know that an id is required to be unique but that's not the same as your claim that it will always be unique. THe rendering will work but any functionality that relies on ids might not
@RuneFS in IE it might be that console.log is not defined and will break the javascript AFAIK.
Cheers for the instant response! It worked like a charm. Do you know how it's possible to make the array add up like this ["Armin van Buuren, "2nd click", "3rd click" etc etc]?
|
0

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 "

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.