Saravanan M P
Saravanan M P

Reputation: 631

jquery to show div one by one each click event

This is my code :

   <script type="text/javascript">
    $(document).ready(function(){
        $('.toAdd').hide();
        $('#add').click(function () {
            var i = 0;
            $('.toAdd').each(function () {
                if ($(this).show()) {
                    i++;
                }
            });
        });
    });
    </script>

    <div id=add><input type="button" value="click"/>
    </div>
    <div id="toAdd">
    <label>1</label>
    </div>
    <div id="toAdd">
    <label>2</label>
    </div>
    <div id="toAdd">
    <label>3</label>
    </div>
    <div id="toAdd">
    <label>4</label>
    </div>

In this code i need to show div one by one for each click event but its not working?

Upvotes: 0

Views: 4556

Answers (5)

bipen
bipen

Reputation: 36531

change id to class, like other have said and if you need to cycle the show/hide. then this might come handy

 $('.toAdd').hide();
 var i = 0;
 $('#add input').click(function () {
     i=(i >= 4)?0:i;
      //or if(i >= 4){ i=0;}
     $('.toAdd').eq(i).show().siblings().not(':first').hide();
     i++;

 });

fiddle here

Upvotes: 0

Barmar
Barmar

Reputation: 781120

As others have said, you need to change id="toAdd" to `class="toAdd".

You can then show the first unhidden DIV with:

    $('#add input').click(function () {
        $('.toAdd:hidden:first').show();
    });

FIDDLE

Upvotes: 2

Vucko
Vucko

Reputation: 20834

ID must be unique, use classes instead.

$('.toAdd').hide();

var count = 0;
$('input').on('click',function(){
    $('.toAdd:eq('+count+')').show();
    count++;
});

JSFiddle

Upvotes: 6

William Buttlicker
William Buttlicker

Reputation: 6000

Replace <div id="toAdd"> with <div class="toAdd">

and do this

  $('.toAdd').each(function () {
                if (!$(this.is(":visible"))) {
                   $(this).show();
                   break;
                }
            });

Upvotes: 0

syned
syned

Reputation: 2321

In your divs change id="toAdd" to class="toAdd"

Upvotes: 2

Related Questions