Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find class and get the value

I am trying to get the value of an input text field.

the HTML is:

<div id="start">     <p>         <input type="text" class="myClass" value="my value" name="mytext"/>     </p> </div> 

The jquery is:

var myVar = $("#start").find('myClass').val(); 

The problem is that myVar is coming up undefined. Does anyone know why?

like image 255
Jason Avatar asked Mar 13 '11 05:03

Jason


People also ask

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do I find the value of a class name?

The syntax is as follows:var elements = document. getElementsByClassName(name); Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.

What is find () in jQuery?

jQuery find() Method The find() method returns descendant elements of the selected element. A descendant is a child, grandchild, great-grandchild, and so on. The DOM tree: This method traverse downwards along descendants of DOM elements, all the way down to the last descendant.

How do you select all elements with the same class?

To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');


2 Answers

Class selectors are prefixed with a dot. Your .find() is missing that so jQuery thinks you're looking for <myClass> elements.

var myVar = $("#start").find('.myClass').val(); 
like image 187
BoltClock Avatar answered Sep 21 '22 09:09

BoltClock


var myVar = $("#start").find('.myClass').first().val(); 
like image 21
user2907730 Avatar answered Sep 18 '22 09:09

user2907730