jquery find class and get the value

JqueryJquery Selectors

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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();

Solution 2 - Jquery

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

Solution 3 - Jquery

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>.

Solution 4 - Jquery

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

Solution 5 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonView Question on Stackoverflow
Solution 1 - JqueryBoltClockView Answer on Stackoverflow
Solution 2 - Jqueryuser2907730View Answer on Stackoverflow
Solution 3 - JqueryDuckMaestroView Answer on Stackoverflow
Solution 4 - JquerySoura GhoshView Answer on Stackoverflow
Solution 5 - JquerySandeep SherpurView Answer on Stackoverflow