Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 256
bhooks Avatar asked Jul 02 '26 16:07

bhooks


1 Answers

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

like image 136
dcodesmith Avatar answered Jul 04 '26 04:07

dcodesmith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!