bhooks
bhooks

Reputation: 419

this.value returns undefined on a td value

I am trying to get the value of a specific within a table. Using the following jQuery:

$( 'td.calendar-day' ).click(function() {
console.log(this);

Returns

<td class="calendar-day" value="2014-01-03">
<div class="day-number">3</div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<div class="class"><a href="http://website.com" target="_blank">2</a></div>
<p>&nbsp;</p>
<p>&nbsp;</p>
</td>

When I click on the following cell

<td class="calendar-day" value="2014-01-03">

However when I add:

console.log(this.value);

It returns: undefined

Any help would be greatly appreciated. Thanks!

Upvotes: 2

Views: 9411

Answers (4)

dcodesmith
dcodesmith

Reputation: 9614

Use the data-* attribute. A table row isn't supposed to have a value attribute. Best practise would be to set a data attribute and then grab it

HTML

<td class="calendar-day" data-value="2014-01-03">

Js

$('td.calendar-day').click(function() {
    this.getAttribute('data-value') // compatible with all browsers and also the most performance efficient. See benchmark below
    // Or .. $(this).data('value')
    // Or .. this.data.value
}

Benchmark Test Courtesy of @crush

Upvotes: 8

James Hibbard
James Hibbard

Reputation: 17735

You can do this:

console.log(this.getAttribute("value"));

but as has been noted, a table row isn't supposed to have a value attribute.

Upvotes: 1

Nouphal.M
Nouphal.M

Reputation: 6344

Try

 $( 'td.calendar-day' ).click(function() {
   console.log($(this).attr('value'));
});

Upvotes: 4

Paddy
Paddy

Reputation: 33857

Try this instead:

console.log($(this).prop("value"));

Upvotes: 0

Related Questions