TeeJay
TeeJay

Reputation: 119

javascript confirm doesnt stop submitting form

i am trying to do a confirm function using javascript in php which it worked only in showing the buttons but whatever you press the form will submit heres the code and the function

<form action='Allocated.php' method='post'  >
    <input type='submit' name='disc' value='Discontue Asset'    formnovalidate='formnovalidate' onclick='myFunction()' />
    <input type='hidden' name='alloc' value='$AllocID' />
    </td>
</form>

and the function

function myFunction() {
    var r = confirm("Press a button!");
    if (r == true) {
        return true;
    } else {
        return false;
    }
}

any help would be appreciated THanks

Upvotes: 0

Views: 896

Answers (4)

S&#243;sthenes Neto
S&#243;sthenes Neto

Reputation: 27

Put this function at attribute onsubmit (with return keyword, thx Scott) on form and change to button

<form action="Allocated.php" method="post" onsubmit="return myFunction()">
    <input type="hidden" name="alloc" value="$AllocID" />
    <button type="submit">Discontue Asset</button>
</form>

Upvotes: 1

Scott Marcus
Scott Marcus

Reputation: 65806

Change onclick='myFunction()' to onsubmit='return myFunction()' so that the returned value from the function can be returned to the event.

Upvotes: 3

Nikunj Sardhara
Nikunj Sardhara

Reputation: 638

You can try code below, It's much simpler

Give an id to your form

<form action='Allocated.php' method='post' id="myform">
<input type='submit' name='disc' value='Discontue Asset'    formnovalidate='formnovalidate' onclick='myFunction()' />
<input type='hidden' name='alloc' value='$AllocID' />
</td>

Then write your javascript like this

function myFunction() {
var r = confirm("Press a button!");
if (r) {
    document.getElementById('myform').submit();
} else {
    return false;
}

}

Upvotes: 0

Pooya Behravesh
Pooya Behravesh

Reputation: 304

use this:

function myFunction() {
    var r = confirm("Press a button!");
    if (r) {
        return true;
    } else {
        return false;
    }
}

or: for booleans you must use === instead of == :

function myFunction() {
    var r = confirm("Press a button!");
    if (r == true) {
        return true;
    } else {
        return false;
    }
}

or

function myFunction() {
    var r = confirm("Press a button!");
    if (r === 1) {
        return true;
    } else {
        return false;
    }
}

Upvotes: 0

Related Questions