Ashley Brown Ashley Brown - 2 months ago 10
jQuery Question

How can I select only the first occurrence of this class?

I have this markup.

<form>
<fieldset id="step-1">
<!-- form code-->
<a class="previous"></a>
<a class="next"></a>
</fieldset>

<fieldset id="step-2">
<!-- form code-->
<a class="previous"></a>
<a class="next"></a>
</fieldset>

<fieldset id="step-3">
<!-- form code-->
<a class="previous"></a>
<a class="next"></a>
</fieldset>

</form>


My jQuery

$('.previous').on('click', function(evr) {
evr.preventDefault();
if ($(this).closest('fieldset').not('#step-1')){
$(this).parent('fieldset').slideUp(function(){
$(this).prev('fieldset').slideDown(); // this doesn't work
});
}
});
$('.next').on('click', function(e){
e.preventDefault();
if ($(this).closest('fieldset').not('#step-3')){
$(this).closest('fieldset').slideUp();
$(this).closest('fieldset').next('fieldset').slideDown();
}
else if ($(this).closest('fieldset').is('#step-3')) {
$('#step-3').slideUp();
}
});


I'm trying to create a multi-step modal where each fieldset will hide itself when you click the next button. The problem I'm having is the previous button. I can't seem to select the first fieldset from the second fieldset's previous button.

How can I select the previous fieldset? This should additionally work from #step-3, too.

Answer

You can use first and last method and psudo selector in jquery

$('.previous').not(':first').on('click', function(e) {
    e.preventDefault();
    $(this).parent('fieldset').slideUp(function(){
       $(this).prev('fieldset').slideDown(); // this doesn't work
    });

  });
  $('.next').not(':last').on('click', function(e){
        e.preventDefault();
        $(this).closest('fieldset').slideUp();
        $(this).closest('fieldset').next('fieldset').slideDown();
  });

$('.previous:first').click(function(e){
    console.log('first prev clicked');
});
$('.next:last').click(function(e){
    console.log('last next clicked');
     $('fieldset:last').slideUp();
})