Here's a screenshot of my chrome javascript console demonstrating my dilemma.
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!
Get Attributes - attr() The jQuery attr() method is used to get attribute values.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With