开发者

How can I find an element by 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" 开发者_StackOverflow中文版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?


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


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


You can also get the value by the following way

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜