Friends, in this article, we will see how to refer to previous and next controls present on a HTML page using jQuery.
jQuery provides 2 very useful functions .prev() and .next() to 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 as in the following:
- <div id="div1">
- <input type="text" id="d1t1" />
- <input type="text" id="d1t2" />
- <input type="text" id="d1t3" />
- </div>
- <div id="div2">
- <input type="text" id="d2t1" />
- <input type="text" id="d2t2" />
- <input type="text" id="d2t3" />
- </div>
In the preceding example, you can traverse between textboxes with ID 'd1t1' and '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 multiple 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, let's see the following jQuery snippet:
- <script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
- <script type="text/javascript">
- $(function () {
- $("#d1t2").focusout(function () {
- alert($(this).prev().val());
- alert($(this).next().val());
- });
- });
- </script>
In the preceding snippet, I have handled the focusout() event for the TextBox ID "d1t2". We use the .prev() and .next() functions to get the value of the textboxes with ID 'd1t1' and 'd1t3' respectively.I hope this gives you a brief insight on how the .prev() and .next() functions work. In case you have any questions, let me know.Keep learning & sharing!