Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: cannot fetch the "value" attribute of a div

Here's a screenshot of my chrome javascript console demonstrating my dilemma.

screenshot of my chrome javascript console demonstrating cannot fetch the "value" attribute of a div

I seriously cannot understand why i can't fetch the "value" attribute. The "class" attribute works just fine, so i figure the same should apply to "value". The code (coffeescript) i'm testing in my app looks like this:

$ ->
  $(".comment").click ->
   alert $(this).attr 'value'

Neither this nor the code shown in this pic work.

Does anyone know what i'm doing wrong or what i SHOULD be doing? Thanks in advance!

like image 339
dcastro Avatar asked Jul 31 '11 03:07

dcastro


People also ask

How to get an attribute in jQuery?

Get Attributes - attr() The jQuery attr() method is used to get attribute values.

What is data() in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.

How set value to data attribute in jQuery?

To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.


1 Answers

Use .val(). This will work only on select, input, textarea tags. For other tags, value attribute is not valid.

If you're using latest jQuery, use data- attirbutes instead:

<div class="comment" data-value="64">

 var value = $('[div selector]').data('value');
like image 128
Mrchief Avatar answered Nov 09 '22 22:11

Mrchief