Kazik Kazik - 5 months ago 20
jQuery Question

How to select next ul on click event using jQuery

I was looking in other questions, but I couldn`t find answer.

I have code like this:

<div class="chacter_form">
<form id="new_character" class="new_character" method="post" accept-charset="UTF-8" action="/users/1/characters">
<ul class="no_dot form_partial active_partial"></ul>
<ul class="no_dot hide form_partial test"></ul>
<ul class="no_dot hide form_partial"></ul>
</form>
<button id="prev_form_button"></button>
<button id="next_form_button"></button>
</div>


Of course every
ul
has some number of
li
. I want to write a jQuery function that when
#next_form_button
is clicked it will hide first
ul
and show the second.
hide
class set display to none.

This is my attempt but it is not working:



$(document).on('click', '#next_form_button', function(){
$active_partial = $('ul.active_partial')
$next_partial = $('ul.active_partial').next('ul')
$active_partial.removeClass('active_partial').fadeToggle()
$next_partial.addClass('active_partial').fadeToggle()
});


Any help would be appreciated

Answer

Use can use :visible selector to finding visible ul and use next() to finding next ul.

$("#next").click(function(){
    if ($("ul:visible").index() < 2)
        $("ul:visible").hide().next().show();
});

$("#prev").click(function(){
    if ($("ul:visible").index() > 0)
        $("ul:visible").hide().prev().show();
});
ul:nth-child(2),
ul:nth-child(3) {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <ul>
        <li>A</li>
        <li>B</li>
        <li>C</li>
    </ul>
    <ul>
        <li>D</li>
        <li>E</li>
        <li>F</li>
    </ul>
    <ul>
        <li>G</li>
        <li>H</li>
        <li>I</li>
    </ul>
    <button id="prev">Prev</button>
    <button id="next">Next</button>
</div>

Comments