2016-03-22 38 views
-1

我有一個調用checkTax()函數的HTML按鈕。 該功能應確認並單擊確定後繼續進行表單提交,或取消提交併將用戶重定向到其他頁面。JavaScript/window.confirm函數的問題

這是函數:

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"); 

     } 
    } 

} 

我曾經嘗試都只是取消提交或重定向,但我不能讓任何工作。兩種方式仍然提交表格並繼續。 我在做什麼錯?

+2

你用什麼代碼來調用這個函數。你能表明一下嗎? – putvande

+0

作爲參考,JS使用'/ /'作爲單行註釋。您包含HTML評論,這可能會破壞您的腳本。 – DBS

+0

相關:[如何防止表單被提交?](http://stackoverflow.com/q/3350247/4642212) – Xufox

回答

0

確保在按鈕的onclick屬性中使用return語句。

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

否則,該函數的返回值將被忽略,它不會阻止的形式從當它返回false提交。

+0

這就是我做錯了的事情,我需要將」return「添加到onClick。Works萬分感謝。 –

0

我已經嘗試完成上面的答案爲您的簡化。 請找到下面的代碼:

<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>