Rajeev
Rajeev

Reputation: 46909

get a div value from jquery

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

Answers (4)

bipen
bipen

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

Anujith
Anujith

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

Tom Bird
Tom Bird

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

Arun P Johny
Arun P Johny

Reputation: 388316

alert($('#div1').attr('value'));

Should do the trick. All attributes of an element can be read and set via jQuery.attr()

Working demo

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

Related Questions