2016-02-28 52 views
0

我做了一個表格及其ATTR設置爲onsubmit="return false"JQuery的:如何發送表單之前執行代碼

現在我需要之前的實際執行一些動作提交這樣的:

$('input[name=submit]').click(function(){ 
    $('.switch-input').attr('checked','checked');//getting all values of chbz 
    //here goes a little more code// 
    $('form[name=setform]').removeAttr('onsubmit');//finally sending to $_POST 
}); 

在第一一目瞭然一切工作正確,但我不知道它會100%執行所有代碼之前發送或我做錯了嗎?

+0

是否有任何不工作?我們可以以某種方式重現它嗎? – Rayon

+0

'$('。switch-input')。attr('checked','checked');'不會獲得'chbz'的所有值,但它會爲所有匹配的元素設置值... – Rayon

+1

don' t使用點擊按鈕...綁定到表單提交事件....用戶可以使用鍵盤旁路按鈕 – charlietfl

回答

1

onsubmit="return false"屬性將阻止提交表單,因爲它通常是。但是,當用戶單擊提交輸入時,上面的代碼片段將執行一次,刪除onsubmit屬性並使表單能夠正常提交,但用戶必須再次單擊提交才能提交它。

您可以保留現有的片段,並告訴jQuery來明確地提交表單,通過.submit()方法的第三個變化:

$('input[name=submit]').click(function(){ 
    $('.switch-input').attr('checked','checked');//getting all values of chbz 
    //here goes a little more code// 
    $('form[name=setform]').removeAttr('onsubmit');//make the form submittable 
    $('form[name=setform]').submit();//finally sending to $_POST 
}); 

或者,你可以刪除onsubmit="return false"屬性,並且使用的.submit(handler)變化該方法簡化了您的代碼,並保證處理程序將在提交表單之前執行:

$('form[name=setform]').submit(function(){ 
    $('.switch-input').attr('checked','checked');//getting all values of chbz 
    //here goes a little more code// 
}); 
+0

'$('。switch-input')。attr('checked','checked'); // get all chbz的值?看起來不合適.... – Rayon

+0

@RayonDabre你提出了一個很好的觀點。 AndrewBro,你想用這個聲明完成什麼? – Stiliyan

1

您可以考慮取消onsubmit屬性,而是使用您的.click()代碼,並在最後放置返回false。您也可以按照Stiliyan的建議使用.submit()

相關問題