Videron
Videron

Reputation: 43

jQuery Select by ID with variable

I have some code that creates some span tags and each span has its own ID

counter1
counter2
counter4

by its name in the database. Now I'm trying to reach the value of one of them. So, I tried something like this:

var id = // Any number that have a span.
var Counter = $("#counter" + id).val();
alert(Counter);

But, it's just showing "NaN"

Upvotes: 2

Views: 10409

Answers (3)

Jesús Quintana
Jesús Quintana

Reputation: 1813

Mmmmm try:

var Counter = $("#counter" + id).html();

or

var Counter = $("#counter" + id).text();

I´m dont sure, but maybe span dont have "value" attribute.

Upvotes: 1

John Dvorak
John Dvorak

Reputation: 27277

You cannot get a val()ue of a <span>. You have to use html() or text().

Upvotes: 2

nbrooks
nbrooks

Reputation: 18233

Change .val() to .html() to access the innerHtml of an html element. .val() selects the value of an html input element as detailed in the API.

var id = // Any number that have a span.
var Counter = $("#counter" + id).html();
alert(Counter);

Upvotes: 5

Related Questions