Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get a div value from jquery

Tags:

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


});
like image 647
Rajeev Avatar asked Dec 12 '25 14:12

Rajeev


2 Answers

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
});
like image 87
bipen Avatar answered Dec 14 '25 05:12

bipen


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/

like image 40
Tom Bird Avatar answered Dec 14 '25 03:12

Tom Bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!