Get div value from jquery

In the next div, how can I get the value = 12 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


});

      

+3


source to share


4 answers


use jquery attr ()

Get the value of an attribute for the first element in a set of matched elements, or set one or more attributes for each matched element.

try it



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

      

OR

$('#div1').on("click", function(a) {

   alert($(this).attr('value'));  //doesnt work
});

      

+5


source


If you can choose not to use native HTML attributes, you will run into validation problems, html5 data attributes are your best bet. This allows you to create your own attributes suitable for storing this type of data. For example:

<div data-num="12" id="div1">some content</div>

    $('#div1').on('click', function(){
       alert($(this).data('num'));
    });

      



http://api.jquery.com/jQuery.data/

+1


source


$(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()

deprecated, use on()

instead

See DEMO

0


source


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

      

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

Working demo

The jQuery.live method has been deprecated (v1.7) and removed (1.9), so use jQuery.on as shown in the demo.

0


source







All Articles