开发者

Getting the next textbox using the next() function in jquery

I am trying to write some Jquery code that will get the value of the next textbox that is of a class "in". The code I have here isn't working, the value is always undefined. I think I am using the next() function incorrectly but I am not sure, does anybody have any input?

<!DOCTYPE html>
<html>

<bod开发者_JAVA百科y>
<input type="text" class="mm" />
<br>
<input type="text" class="in" />  

$(document).ready(function() {
    $("input").focus(function() {

        var value = $(this).next(".in").val();
        if (value) {
            alert(value);
        }

    });
});   

  </script>
 </body>
</html>


Your example as you've given the HTML actually works. You can see it here: http://jsfiddle.net/jfriend00/RGsDq/. Based on your comments, it sounds like you want the first sibling that has the class "in" whether it's the next sibling or not. .next() only examines the very next sibling. If you want the first sibling that has the class "in" even if it's not the very next sibling, you can do either of these:

$(this).nextAll(".in").first().val();           // next sibling with class ".in"
$(this).parent().find(".in").first().val();     // next child of parent with class ".in"

You can see the first of these two options working here: http://jsfiddle.net/jfriend00/4VwAN/


You would need to post your html. The Next gets the next sibling, so it very much depends on the html structure - it might just need you to add a parent in to get to the point which is a parent of all the text boxes.


$(this).next(".in") will only return a value if the next element has a class of "in", rather than looking at all siblings for the first textbox with a class of "in". Try $(this).nextAll(".in:eq(0)").

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜