2013-08-22 17 views
0

更新UI我有提交一個表單的輸入元素:上的表單後調用Javascript功能來通過jQuery

<input type="submit" value="Download" id="downloadButton" class="btn-download" /> 

我需要的按鈕調用javascript函數,然後發佈形式一般。

這將如何在jQuery中完成?

+1

將輸入類型更改爲按鈕並在您的函數$(「form」)。submit()中添加onClick =「yourFunctionName」。 – HaBo

回答

2
$('#downloadButton').on('click', function (e) { 
    e.preventDefault(); 
    //call your function here 
    $(this).parents('form').submit(); 
}); 

preventDefault()通話非常重要,因爲它停止提交表單,所以你可以調用你的函數形式提交被稱爲在年底之前。

0

jsFiddle here

更改輸入類型type="button"及用途:

$('#downloadButton').click(function() { 
    //Do any javascript stuff here 
    //And here, etc. Then, when ready... 
    $('#yourFormID').submit(); 
}); 

,因爲它是很好的做法,我建議分配一個ID屬性到表單中。

<form id="yourFormID" action="" method="POST"> 

也許你有這個頁面上只有一種形式,在這種情況下$('form').submit()是罰款。但在將來(或者甚至在本頁面上,您還沒有說過),您可能在頁面上有多個表單,因此必須指定要提交的確切表單。

請注意,如果您不將提交按鈕元素的<input type="submit"更改爲<input type="button",那麼您必須使用e.preventDefault()來防止該按鈕的默認操作。爲什麼要打擾呢?只需更改type="button"並使用更少的代碼和更少的未來混淆。

+0

你不需要改變任何東西。 – ncubica

+0

閱讀我的答案。如果你不改變它,那麼OP必須使用e.preventDefault()。爲什麼添加不必要的複雜? – gibberish

+0

好吧你編輯它我看了其他內容...和平兄弟... – ncubica

1

你可以這樣做:

<form onsubmit="return doSomething();"> 
</form> 

function doSomething() { 
    // do something 
    return true; 
} 

如果doSomething功能你不喜歡你所看到的,然後返回false而不是true

編輯

jQuery的當量(以滿足這兩個評論者):從HTML刪除onsubmit,並替換爲:

jQuery(document).ready(function() { 
    jQuery("form#myFormId").submit(doSomething); 
}); 
+1

不好的做法混合JavaScript與HTML ...壞壞! – ncubica

+1

他問它jQuery。 –

1

看看這個jsfiddle

它改變在提交表格之前將文本框內容改爲大寫

$('#formID').on('submit', function() { 

    //var form = $(this), 
    //input = form.find('input[type="text"]'); 
    //input.val(input.val().toUpperCase()); 
    //alert(input.val());   
    // call your function here! 
}); 
0

這就是你要求的: 1.-點擊一個按鈕(添加事件處理程序) 2.-調用函數 3。 - 提交表單

myfunction(){ 
//do wathever you want 
$('#formid').submit(); 
} 

$(document).on("click", "#downloadButton", myfunction); 

你也可以這樣做:

$(document).on("click", "#downloadButton", function(event){ 
    $('#formid').submit(); 
}); 

,而無需額外的功能

但@Paritosh的解決方案是更準確。

0

在表單上添加一個提交事件。

$('form').submit(function(event){ 
    event.preventDefault(); 
    var formObj = $(this); 
    var formData = formObj.serialize(); 
    $.ajax({ 
     type: 'post', 
     data: formData 
    }).done(function(response){ 
     console.info(response); 
     // update UI here accordingly. 
    }); 
}); 
相關問題