Austen Novis
Austen Novis

Reputation: 444

Get value from element in the clicked class

I have multiple instances of the same class with different values inside and I want to write a jquery function that can get the value of the class clicked.Right now my function returns blank.

Here is the html that I have

<div class="named" > <h5 value = "1"> value 1 </h5></div>
<div class="named" > <h5 value = "2"> value 2 </h5></div>

and here is my jquery function

$(".named").click(function(){
console.log($(this).find("h5").val());
});

thank you very much

Upvotes: 0

Views: 8683

Answers (3)

jammykam
jammykam

Reputation: 17000

Try:

$(".named").click(function(){
    console.log($(this).find("h5").attr("value"));
});

You should really be using the data-* attributes and jQuery .data()

<div class="named"> <h5 data-value="1"> value 1 <h5></div>
<div class="named"> <h5 data-value="2"> value 2 <h5></div>

$(".named").click(function(){
    console.log($(this).find("h5").data("value"));
});

Upvotes: 5

raj
raj

Reputation: 817

$(".named").click(function(){
    console.log($(this).find("h5").attr("value"));
});

headers don't take values, so they consider them attributes

Upvotes: 0

Kenneth
Kenneth

Reputation: 28747

value is not a valid attribute of an h5-tag. You should probably change that to data-value(html5) and then either use the attr-method or the jQuery data api:

<div class="named" > <h5 value = "1"> value 1 <h5></div>
<div class="named" > <h5 value = "2"> value 2 <h5></div>

// With attr
$(".named").click(function(){
    console.log($(this).find("h5").attr("data-value");
});

// with the data api
$(".named").click(function(){
    console.log($(this).find("h5").data("value");
});

Upvotes: 2

Related Questions