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?
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.
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.
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.
To select elements by a given class name, you use the getElementsByClassName() method: let elements = document. getElementsByClassName('className');
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();
var myVar = $("#start").find('.myClass').first().val();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With