Doc Holiday
Doc Holiday

Reputation: 10254

Javascript return in function

I need this function to fail and not do the confirm, or submit the form and stay on the page if the sub function comes back false.

   function doDelete()
{
   if (THIS FAILS!()-STAY ON PAGE!) 
       // do something here
if (confirm("Are you sure you want to update and then delete this hot part?"))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Upvotes: 2

Views: 230

Answers (4)

Andrew Rasmussen
Andrew Rasmussen

Reputation: 15099

Returning false from a form submit callback will result in the page not being submitted. You can also just return the result of the confirm, rather than using an if-else.

function doDelete() {
    if (THIS FAILS!()-STAY ON PAGE!) {
        // do something here
        return false;
    }
    return confirm("Are you sure you want to update and then delete this hot part?");
}

Upvotes: 1

Jules
Jules

Reputation: 7213

I assume your HTML is:

<form method="POST" action="page.php" onsubmit="return doDelete()">
   ...
</form>

And your javascript should then be something like:

function doDelete() {
   //if (THIS FAILS!()-STAY ON PAGE!) {
      // do something here
      return (confirm("Are you sure you want to update and then delete this hot part?"));
   //}
}

Something like this you mean? You can simply return the outcome of the confirm() method instead of doing an if-else.

I don't understand what's with the THIS FAILS though. Is this just a general remark of you? If so, leave it out... ;-)

Upvotes: 0

Andreas Louv
Andreas Louv

Reputation: 47099

function doDelete()
{
    if (THIS FAILS!()-STAY ON PAGE!) {
        return false;
    } else {
        return confirm("Are you sure you want to update and then delete this hot part?");
    }
}

Upvotes: 2

Jack Edmonds
Jack Edmonds

Reputation: 33161

You can attach a function to a form that will get called when the user attempts to submit the form. If that function returns false, the form won't be submitted and the user will remain on the page.

Essentially, you can do this:

<script type="text/javascript">
    function doDelete()
    {
        if (THIS FAILS!()-STAY ON PAGE!)
            return false;
        return confirm("Are you sure you want to update and then delete this hot part?");
    }
</script>

<!-- Make doDelete the callback for this form's onsubmit.
     When the user submits the form, doDelete will be called.
     If doDelete returns false, the form will not be submitted
     and the user will remain on the current page. -->
<form onsubmit="doDelete" ...

Upvotes: 0

Related Questions