Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value of ID from class using jQuery?

Tags:

jquery

class

How would you retrieve the value of the ID tag using its class name in jQuery.

I am trying the following code but it returns value undefined.

<html>
    <body>
        <textarea id='5' class='cp _check'>sometexthere</textarea>
    </body>
<html>

And calling it using the following function:

function updatecontent() {
    var check = $('.cp _check').('#id').val();
    alert(check);
}

The alert box returns value as undefined.

like image 257
user2131970 Avatar asked Feb 18 '23 03:02

user2131970


2 Answers

You are looking for attr() or prop().

Since you want to obtain the value of the id HTML attribute, I would emphasize that and go with attr():

var id = $(".cp._check").attr("id");

Your class selector is also incorrect: since your element exposes both the cp and the _check classes, it should be .cp._check instead of .cp _check (which would match the <_check> elements that are descendants of elements that expose the cp class).

like image 120
Frédéric Hamidi Avatar answered Mar 03 '23 23:03

Frédéric Hamidi


Use attr():

$(".cp_check").attr("ID");

Live Demo: http://jsfiddle.net/3WHqS/


It's also perhaps worth nothing your HTML markup has 2 classes, cp and _check. You need to remove the whitespace between the 2 for this to become 1 class: cp_check.

like image 21
Curtis Avatar answered Mar 03 '23 21:03

Curtis