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?
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?
Share Improve this question edited Sep 2, 2013 at 8:01 Barmar 783k56 gold badges546 silver badges660 bronze badges asked Sep 2, 2013 at 7:54 Saravanan M PSaravanan M P 6411 gold badge8 silver badges12 bronze badges 4- First of all 'toAdd' is id, and you used it as a class in jQuery. Use '#' instead of '.' – M Shahzad Khan Commented Sep 2, 2013 at 7:57
-
Actually, use
class
instead ofid
. – Artyom Neustroev Commented Sep 2, 2013 at 7:58 - yes i changed but its not working that whole divisions was at single click event – Saravanan M P Commented Sep 2, 2013 at 8:00
-
Why do you have
$(this).show()
in anif
? It doesn't return a true/false value, it just returns the jQuery object, so that methods can be chained. – Barmar Commented Sep 2, 2013 at 8:02
5 Answers
Reset to default 6ID must be unique, use classes instead.
$('.toAdd').hide();
var count = 0;
$('input').on('click',function(){
$('.toAdd:eq('+count+')').show();
count++;
});
JSFiddle
In your divs change id="toAdd" to class="toAdd"
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
Replace <div id="toAdd"> with <div class="toAdd">
and do this
$('.toAdd').each(function () {
if (!$(this.is(":visible"))) {
$(this).show();
break;
}
});
change id to class, like other have said and if you need to cycle the show/hide. then this might e 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