-1

I have an HTML button that calls the checkTax() function. The function should either confirm and proceed with the form submit when OK is clicked, or cancel the submission and redirect the user to a different page.

This is the function:

function checkTax () {
    if ( CUSTTAXRATE == 0 ) {
        var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
        if (r == true){
            return true;
        }
        else {
        <!---   return false; --->
             window.location.replace("index.cfm?action=retailQuote.settings");

        }
    }

}

I have tried both just cancelling the submission or redirecting it, but I cant get either to work. Both ways still submit the form and proceed. What am I doing wrong??

PEHLAJ
  • 9,980
  • 9
  • 41
  • 53
Wes Loflin
  • 27
  • 1
  • 7
  • 2
    What code do you use to call this function. Can you show that please? – putvande Mar 22 '16 at 16:42
  • For reference, JS uses `//` for single line comments. You're including HTML comments, which could break your script. – DBS Mar 22 '16 at 16:45
  • Related: [How to prevent form from being submitted?](http://stackoverflow.com/q/3350247/4642212) – Sebastian Simon Mar 22 '16 at 16:48
  • This is my button. Sorry about the commenting. I write in coldfusion and I was just trying to show both of the ways that I have tried. – Wes Loflin Mar 22 '16 at 16:52
  • If this is used in the form's `onsubmit` attribute, make sure it's called as `onsubmit="return checkTax()`. – Barmar Mar 22 '16 at 16:52

2 Answers2

0

Make sure you use a return statement in the button's onclick attribute.

<button type="submit" onclick="return checkTax();">Submit</button>

Otherwise, the return value from the function will be ignored, and it won't prevent the form from submitting when it returns false.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I have tried completing the answers above for your simplification. Please find the code below :

<body>
<form action="">
    <input type=text id="t1">
    <button type="submit" onclick="return checkTax();">Submit</button>
</form>

<script type="text/javascript">
    function checkTax() {
        var CUSTTAXRATE = document.getElementById("t1");
        if (CUSTTAXRATE == 0) {
            var r = confirm("Your current tax rate is 0.\n\nIf this is correct click OK to continue.\n\nIf this needs to be adjusted, click CANCEL and visit the quote set up page under DEALER RESOURCES tab.");
            if (r == true) {
                return true;
            } else {
                window.location
                        .replace("index.cfm?action=retailQuote.settings");
                return false;
            }
        }

    }
</script>

Ankur Bag
  • 63
  • 1
  • 1
  • 5