Rohitashv Singhal
Rohitashv Singhal

Reputation: 4557

How to hide the previous li tag in jquery

I am working on a project in which I have a ul tag with 5 li.

What I want to do is that I want to show each Items one by one on the click of a button. Means as I click the button then the next item should be displayd and the previous one should be hide. as generally happens in quizes.

When We click the next button, the next question appears and the previous one hides.

I am using the following html code :

<div class="span12" style="margin-top:140px;">
<ul id="part">
<li id="div0" style="display:none;">Question id</li>
<li id="div1" style="display:none;">Question 2</li>
<li id="div3" style="display:none;">Question 3</li>
<li id="div4" style="display:none;">Question 4</li>
<li id="div5" style="display:none;">Question 5</li>
</ul>
<button id="next">Next</button>
</div>

and the jquery code is :

<script>
$(function(){
    var items = $('ul#part li');
    if(items.filter(':visible').length == 0)
    {
        items.first().show();
    }
    $('#next').click(function(e){
        e.preventDefault();
    items.filter(':visible:last').next().show();
    });
});
</script>

It is showing the next items from ul on button click but I am unable to hide the previous button.

How can I hide the previous li button as I click on next.

Please help me

Upvotes: 1

Views: 1554

Answers (3)

Ajey
Ajey

Reputation: 8212

Working on Arek's answer, change the if condition to

if (next.length) {
  next.show();
} else {
  $('#next').html("Submit");
}

so that the button is changed to submit.

Demo Fiddle

Upvotes: 1

user3161877
user3161877

Reputation: 36

Var index=0;/*this should be global variable*/

('#next').click(function(e){
      e.preventDefault();
      items.hide();
      items[index].show();
      index==items.length-1?index=0:index++;
 });

Upvotes: 0

Arek S
Arek S

Reputation: 4729

This should work

<script>
$(function(){
    var items = $('ul#part li');
    if(items.filter(':visible').length == 0){
        items.first().show();
    }

    $('#next').click(function(e){
        e.preventDefault();

        var active = items.filter(':visible:last');
        active.hide();

        var next = active.next();
        if (next.length)
             next.show();
    });
});
</script>

To check if next exists you should check the length.

Upvotes: 4

Related Questions