alsanal
alsanal

Reputation: 183

get next and previous inputs on button click

I need to get the value of the previous and next input by click on a element styling as a button... Example code:

<ul>
    <li>
        <input type="text">
    </li>
</ul>
<ul>
    <li class="li-inline">
        <a class="btn" href="#">
            <i class=""></i>
        </a>
    </li>
</ul>
<ul>
    <li>
        <input type="text">
    </li>
</ul>

I try with next() and prev() jquery methods but have not achieved the expected results.

$("a").click(function() {
  $(this).next(":input");
});

Upvotes: 3

Views: 1033

Answers (3)

Adil
Adil

Reputation: 148150

First you have to reach the parent ul using closest() and then go to next or previous ul using next() or prev() respectively and find input in the descendants using find()

Live Demo

$("a").click(function() {
     $(this).closest('ul').prev('ul').find(":input");
     $(this).closest('ul').next('ul').find(":input");
});

Upvotes: 3

Sridhar Narasimhan
Sridhar Narasimhan

Reputation: 2653

Try below code

$("a").click(function() {

var previous =   $($(this).closest('ul').prev('ul').find.(":input").get(0)).val();

var next=   $($(this).closest('ul').next('ul').find.(":input").get(0)).val();
});

Thanks

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

Try this:

$("a").click(function() {
    var $a = $(this);
    var prevInputValue = $a.closest('ul').prev().find('input').val();
    var nextInputValue = $a.closest('ul').next().find('input').val();
});

In your original code, next() doesn't work because the input elements are not siblings of the a. You need to traverse the DOM to find the relevant ul which contains them.

Upvotes: 0

Related Questions