更新UI我有提交一個表單的輸入元素:上的表單後調用Javascript功能來通過jQuery
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
我需要的按鈕調用javascript函數,然後發佈形式一般。
這將如何在jQuery中完成?
更新UI我有提交一個表單的輸入元素:上的表單後調用Javascript功能來通過jQuery
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
我需要的按鈕調用javascript函數,然後發佈形式一般。
這將如何在jQuery中完成?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
的preventDefault()
通話非常重要,因爲它停止提交表單,所以你可以調用你的函數形式提交被稱爲在年底之前。
更改輸入類型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"
並使用更少的代碼和更少的未來混淆。
你可以這樣做:
<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);
});
不好的做法混合JavaScript與HTML ...壞壞! – ncubica
他問它jQuery。 –
看看這個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!
});
這就是你要求的: 1.-點擊一個按鈕(添加事件處理程序) 2.-調用函數 3。 - 提交表單
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
你也可以這樣做:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
,而無需額外的功能
但@Paritosh的解決方案是更準確。
在表單上添加一個提交事件。
$('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.
});
});
將輸入類型更改爲按鈕並在您的函數$(「form」)。submit()中添加onClick =「yourFunctionName」。 – HaBo