How To Find Class In Jquery
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?
Ryan M
13.8k 26 gold badges 51 silver badges 62 bronze badges
asked Mar 13 '11 at 5:40
JasonJason
2,567 3 gold badges 26 silver badges 39 bronze badges
5 Answers 5
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();
answered Mar 13 '11 at 5:42
BoltClock♦ BoltClock
647k 151 gold badges 1319 silver badges 1303 bronze badges
6
var myVar = $("#start").find('.myClass').first().val();
p.s.w.g
139k 27 gold badges 269 silver badges 309 bronze badges
answered Dec 10 '13 at 20:57
var myVar = $("#start").find('myClass').val();
needs to be
var myVar = $("#start").find('.myClass').val();
Remember the CSS selector rules require "." if selecting by class name. The absence of "." is interpreted to mean searching for <myclass></myclass>
.
answered Mar 13 '11 at 5:43
DuckMaestroDuckMaestro
13.9k 10 gold badges 64 silver badges 84 bronze badges
0
You can also get the value by the following way
$(document).ready(function(){ $("#start").click(function(){ alert($(this).find("input[class='myClass']").val()); }); });
answered Aug 17 '19 at 16:30
You can get value of id,name or value in this way. class name my_class
var id_value = $('.my_class').$(this).attr('id'); //get id value var name_value = $('.my_class').$(this).attr('name'); //get name value var value = $('.my_class').$(this).attr('value'); //get value any input or tag
answered Aug 29 '16 at 4:44
Not the answer you're looking for? Browse other questions tagged jquery jquery-selectors or ask your own question.
How To Find Class In Jquery
Source: https://stackoverflow.com/questions/5287736/jquery-find-class-and-get-the-value
Posted by: lainezdrinnera76.blogspot.com
@Jason: You may want to post the actual code. I have a gut feeling it's not as simple as it looks.
Mar 13 '11 at 5:44
Your right. This is a watered down version of the code to simplify it. It appears the concept should work.
Mar 13 '11 at 5:48
@Jason can you please post the solution, I have a feeling we are doing the same thing.
Sep 8 '13 at 1:30
@Zaibis: The original code wasn't the same - look at the revision history. Frankly I think the question should be closed since it seems to have been a different problem and we haven't been given much to go on.
Apr 25 '14 at 6:45
Would be best as he says "This is not working: 'correct working queryy'" -> this Was just confusing me untill I realized that he eddited his question.
Apr 25 '14 at 6:46