Reputation: 2510
I would like to create a simple form / page step by step without using a plugin already cooked. To do this I did it this way and it works well.
HTML
<div id="p1">
<input class="goto2" type="button" value="next" />
</div>
<div id="p2">
<input class="goto1" type="button" value="prev" />
<input class="goto3" type="button" value="next" />
</div>
<div id="p3">
<input class="goto2" type="button" value="prev" />
</div>
CSS
#p2, #p3 {
display: none;
}
JS
$(".goto1").click(function() {
$('#p2').hide('slow');
$('#p1').show('slow');
});
$(".goto2").click(function() {
$('#p1').hide('slow');
$('#p3').hide('slow');
$('#p2').show('slow');
});
$(".goto3").click(function() {
$('#p2').hide('slow');
$('#p3').show('slow');
});
I'd like to do this with a cleaner code, perhaps using the toggle function? Is it possible? Thanks
Upvotes: 1
Views: 127
Reputation: 879
You can use this :
$("input:button").on("click", function () {
var $this = $(this);
var parentId = $this.parent().attr("id");
switch (parentId) {
case "p1":
$('.to1').slideToggle();
break;
case "p2":
$this.hasClass("goto1") ? $('.to1').slideToggle() : $('.to2').slideToggle()
break;
case "p3":
$('.to2').slideToggle();
break;
}
});
and for html:
<div id="p1" class="to1">
<input class="goto2" type="button" value="next" />
</div>
<div id="p2" class="to1 to2">
<input class="goto1" type="button" value="prev" />
<input class="goto3" type="button" value="next" />
</div>
<div id="p3" class="to2">
<input class="goto2" type="button" value="prev" />
</div>
Here is the fiddle: http://jsfiddle.net/5y28h75w/9/
Upvotes: 1
Reputation: 33218
I would just check if element has specific class:
$("input:button").on("click", function () {
if ($(this).hasClass("goto1")) {
$('#p2').hide('slow');
$('#p1').show('slow');
} else if ($(this).hasClass("goto2")) {
$('#p1, #p3').hide('slow');
$('#p2').show('slow');
} else {
$('#p2').hide('slow');
$('#p3').show('slow');
}
});
Upvotes: 2