Reputation: 46909
In the following div how can i get the value=12 value when the div is clicked
<div value='12' id='div1'>some content</div>
$('#div1').live("click", function(a) {
alert(this.value);
alert($('#div1').val()); //doesnt work
});
Upvotes: 3
Views: 12006
Reputation: 36531
use jquery attr()
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
try this
alert($('#div1').attr('value'));
OR
$('#div1').on("click", function(a) {
alert($(this).attr('value')); //doesnt work
});
Upvotes: 5
Reputation: 9370
$(document).on("click", '#div1', function(a) {
alert(this.attributes["value"].nodeValue);
alert(this.attributes["value"].value);
alert(this.getAttribute("value"));
alert($('#div1').attr("value"));
});
live()
is deprecated, Use on()
instead
See DEMO
Upvotes: 0
Reputation: 1039
If you can keep away from using your own HTML attributes you'll run into validation issues, a better choice would html5's data attributes. This allows you to create your own attributes good for holding this type of data. For instance:
<div data-num="12" id="div1">some content</div>
$('#div1').on('click', function(){
alert($(this).data('num'));
});
http://api.jquery.com/jQuery.data/
Upvotes: 1
Reputation: 388316
alert($('#div1').attr('value'));
Should do the trick. All attributes of an element can be read and set via jQuery.attr()
The jQuery.live method is deprecated(v1.7) and removed(1.9), so please use jQuery.on instead as shown in the demo.
Upvotes: 0