April 27, 2015 by Nitesh

How To Refer Next & Previous Controls on HTML Page Using jQuery


In this post, we will see how can we refer to previous and next controls present on an HTML page using jQuery.

jQuery provides 2 very useful functions .prev() and .next() with the help of which we can refer to the immediate previous/next sibling of a given control. This is to be noted that these functions limit to the current reference of a DOM element.

From the jQuery documentation –

.prev() gets the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector

.next() gets the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.

Let’s see it in action –

    <div id="div1">
       <input type="text" id="d1t1" />
       <input type="text" id="d1t2" />
       <input type="text" id="d1t3" />
    <div id="div2">
       <input type="text" id="d2t1" />
       <input type="text" id="d2t2" />
       <input type="text" id="d2t3" />

In the above example, you can traverse between text boxes with ID ‘d1t1’, ‘d1t2’ and ‘d1t3’ or ‘d2t1’, ‘d2t2’ and ‘d2t3’ using the .prev() and .next() functions. You will not be able to traverse between ‘d1t1’ and ‘d2t1’ using these functions because they are contained in different parent div blocks. However, you can traverse between ‘div1’ and ‘div2’ using .prev() and .next() functions because they are immediate siblings.

Considering the same example above, lets see the below jQuery snippet now –

    <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script type="text/javascript">
            $(function () {            
                $("#d1t2").focusout(function () {

In the above snippet, I have handled focusout() event for the textbox ID “d1t2”. We use the .prev() and .next() functions to get the value of text boxes with ID ‘d1t1’ and ‘d1t3’ respectively.

Hope this gives you a brief insight on how .prev() and .next() functions work. In case you have any questions, let me know.

Keep learning & sharing!


Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup