[英]Jquery stop submit and get data from form
我正在嘗試使用jquery從表單中獲取數據並使用此代碼停止表單提交:
$form = $('form#signup')
$form.submit(function(event){
event.preventDefault();
var $input=$('#signup :input')
console.log($input.username)
alert($input.username)
})
但是表單仍然post
數據並且沒有出現警告框。另外firebug會顯示錯誤$ is not defined
且Node.js崩潰
形式(寫在玉):
html
head
script(src='javascripts/signupValidation.js')
script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js')
script(src='javascripts/validator.js')
body
form(id='signup',method='post',action='/signup')
label Firstname
input(type='text', name='firstname')
label Lastname
input(type='text', name='lastname')
label Username
input(type='text', name='username')
label Password
input(type='password', name='password')
label Password again
input(type='password', name='password2')
label Email
input(type='email', name='email')
input(type='submit',value='Sign up', onclick="")
如果你的表單相關的JS是在文件signupValidation.js
,你需要移動腳本調用包含該文件是后 jquery的包括。
我可能也會稍微清理一下表單代碼:
$('form#signup').on('submit', function(event){
event.preventDefault();
var $input = $(this).find('[name=username]');
console.log($input.val());
alert($input.val());
})
您可能也有興趣查看.serialize()
。
您需要阻止表單提交return false
:
$form.submit(function(event){
var $input=$('#signup :input');
console.log($input.username);
alert($input.username);
// data = array of all the information collected from the input tags
//data = $form.serizalize(); will also work
data = $(this).serialize();
return false;
});
data
將是一個包含您需要的信息的數組,我建議使用console.log(data)
以便您可以看到它的所有結構,然后您可以根據需要使用它,例如:
if(data.something == anything){
doThis();
}
我強烈建議添加;
在你的javascript語句結束時
您的代碼出現問題[表單提交沒有問題]
$input.username
是無效的jQuery引用另一個元素。
var usernameInput = $input.filter('[name="username"]');
看起來你沒有在document.ready上添加代碼,所以你可能沒有把它附加到任何東西。 將其更改為:
jQuery( function() {
$form = $('form#signup');
$form.submit(function(event){
});
}
您還可以在jQuery代碼之前包含驗證代碼。 我打賭在瀏覽器中查看JavaScript控制台有一些很好的錯誤消息。
和其他人一樣,我對這樣的代碼運氣不錯:
$(document).ready(function(){
// Prevent form submission
$( "form" ).submit(function( event ) {
event.preventDefault();
});
});
防止表單提交。 但是,現在很常見的是,頁面上的腳本會在你的背后添加,並添加一些糖果塗層功能,如動畫和“抖落”效果到HTML表單。 這些腳本可能會在這種情況下妨礙,因為它們可能有自己的javascript-fu用於提交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.