user2603267
user2603267

Reputation: 15

jquery go to previous parent element

I'm trying to make a form by steps and when i'm on the 3 step and try to go to the previous step(2) it goes right to the first step, im using the next() and prev(), the code is in the fiddle.

Thanks for the help

http://fiddle.jshell.net/zo9gnk8c/3/

Upvotes: 0

Views: 542

Answers (4)

Web pundit
Web pundit

Reputation: 498

when you click on the goback link, it reloads the page as it is an <a> tag with a blank href. In order to stop the default behaviour add an event to your goback click function and stop the default action

$(".goback").click(function(e) {
   e.preventDefault();
   // Do something - your logic
});

Upvotes: 0

K K
K K

Reputation: 18099

Use return:false; or e.preventDefault() at the end of your code

Demo: http://fiddle.jshell.net/zo9gnk8c/4/

JS:

    $(document).ready(function () {
    $("button").click(function (e) {
        if ($(this).parent().next("fieldset").length > 0) {
            $(this).parent().toggle();
            $(this).parent().next().toggle();
        }
        return false
    });
    $(".goBack").click(function (e) {
        if ($(this).parent().prev("fieldset").length > 0) {
            $(this).parent().toggle();
            $(this).parent().prev("fieldset").toggle();
        }
        return false;
    });
});

Upvotes: 0

Cerlin
Cerlin

Reputation: 6722

Check this

You have to suppress the anchor click

$("button").click(function(){
    if($(this).parent().next("fieldset").length > 0){
        $(this).parent().toggle();
        $(this).parent().next().toggle();
    }
});
$(".goBack").click(function(e){
    e.preventDefault(); // Added this new line
    if($(this).parent().prev("fieldset").length > 0){
        $(this).parent().toggle();  
        $(this).parent().prev("fieldset").toggle();
    }
});

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

set href to # for anchor tags to prevent page refresh:

<a href="#" class="goBack">Previous</a>

Working Demo

Upvotes: 0

Related Questions