2014-02-10 123 views
0

我有一個提交按鈕,如下所示。使用JavaScript按下提交按鈕時更改表單動作

<input type="submit" 
     name="btnDelete" 
     id="btnDelete" 
     value="Delete" 
     onclick="this.form.action='${pageContext.request.contextPath}/Country/DeleteMany'"/> 

當按下按鈕時,會導致表單動作改變。


但是,我需要在這個動作改變之前調用另一個函數。這個另一個函數根據JavaScript的確認對話框返回一個布爾值。

我試過以下。

onclick="return confirmDeleteMuliple(); this.form.action='${pageContext.request.contextPath}/Country/DeleteMany'" 

的動作卻並沒有改變提交(當confirmDeleteMuliple()返回true)。


我已經嘗試將代碼更改爲單獨的JavaScript函數,如下所示。

function deleteManyAction() 
{ 
    document.dataForm.action='${pageContext.request.contextPath}/Country/DeleteMany'; 
} 

onclick屬性更改如下。

onclick="return confirmDeleteMuliple();deleteManyAction();" 

但是deleteManyAction()函數從來沒有被調用。它僅在從onclick中刪除功能confirmDeleteMuliple()時起作用。

如何在定義的序列中調用這兩個函數?

表達式${pageContext.request.contextPath}在加載時評估爲應用程序的上下文路徑,如/Example(此文件(JSP)被解析時)。

+1

看來你正在尋找'的JavaScript onsubmit'事件.. –

+0

無論如何,動作應該被確認後(變更後'confirmDeleteMuliple()'返回否則,什麼都不應該發生)。 – Tiny

+0

然後,當它返回true時,應該在'confirmDeleteMultiple'函數中調用下一個函數。 –

回答

1

永遠不會到達return之後的代碼。 return基本上意味着停止工作,並給我你所擁有的。

這應該做你想要什麼:

onclick="return submit();" 

function submit(){ 
    if(confirmDeleteMuliple()){ 
     deleteManyAction(); 
     return true; 
    }else{ 
     return false; //Otherwise the form will be submitted anyway. 
    } 
} 
1

儘量保持代碼(JS)出你的表示層(HTML)的。我將我的所有事件處理程序分配在我的JS文件中。試試這個辦法,我認爲這會讓你的代碼:

$("#btnDelete").click(function() { 
    if (confirmDeleteMuliple()) { 
     this.closest("form").attr("action", 
           ${pageContext.request.contextPath} + '/Country/DeleteMany'); 
     # Here, returning true will allow the form submission to complete with the new 
     return true; 
    } else { 
     # This will stop the form from being submitted 
     return false; 
    } 
});