2015-11-13 129 views
-1

我有這樣的腳本:JQuery的提交()不工作

<form action="" method="POST" id="regform"> 
    <paper-material id="general"> 
      <gold-email-input pw="mail" name="mail" label="Mail" auto-validate></gold-email-input> 
      <paper-input id="pw" name="pw" type="password" label="Password"></paper-input> 
      <paper-input id="pwrepeat" type="password" label="Repeat password"></paper-input> 

      <paper-button onClick="subform();" id="submitbutton" elevation="2" raised>Submit</paper-button> 
    </paper-material> 
</form> 

 

function subform(){ 
     console.log("call"); 
     $('#regform').submit(function(e){ 
      console.log("Data: " + $(this).serialize()); 
      e.preventDefault(); //no difference with or without this function    
     }); 
    } 

方法submit(function(e))不是由腳本調用。爲什麼?我想阻止提交和使用數據。這是從表單中分離數據的正確方法嗎?

+0

您是否嘗試過取出'e.preventDefault();'? – Haring10

+0

您正在阻止提交功能,而不是默認的表單操作 –

+1

您爲什麼要設置按鈕上的事件處理程序?這沒有意義 – epascarello

回答

1

如您的代碼所示,函數可能調用,具體取決於您的JavaScript代碼所在的位置。

一般而言,使用onClick不鼓勵,因爲它可能會導致討厭的範圍界定問題。在這一點上,html解析器通過onclick="subform();"達到您的輸入,此功能必須註冊到全局範圍。這是而不是的情況下,如果您使用$(document).ready或者在頁面底部有JavaScript。

因此,請檢查您的控制檯是否有錯誤,因爲您應該看到console.log("call");或錯誤消息,而這會首先阻止執行您的功能。

此外,在onClick處理程序中,您只需爲submit事件註冊一個處理程序,那麼您完全可以直接跳過它,並直接註冊提交處理程序。

您的代碼應該簡單地看是這樣的:

// this waits until your form is submitted 
$('#regform').submit(function(e){ 
    console.log("submit button was pressed"); 
    console.log("Data: " + $(this).serialize()); 
    // this prevents the the actual form submit, so you have to do 
    // some kind of ajax call, to get the data to the server 
    e.preventDefault();    
}); 
+0

謝謝,這是工作,但我必須註冊提交按鈕通過'$(「#regform」)提交表單。submit()' –

+0

@SeseSchneider我不熟悉聚合物 - 在純html中,默認操作的按鈕是提交動作,但這可能不適用於聚合物。 – Christoph

-2

嘗試指定您的提交按鈕的輸入類型。

<input type="submit" class="paper-button" onClick="subform();" id="submitbutton" elevation="2" raised>Submit</paper-button> 

另外,preventdefault將阻止提交。嘗試刪除它。

編輯:

克里斯托弗指出,圖書館正在被使用,因此選擇一個是行不通的。相反,請刪除preventdefault。

+0

正在使用聚合物庫而不是HTML語言如果你不熟悉它,請查看:https ://www.polymer-project.org/ –

+0

我想阻止表單提交使用Ajax,但我必須使用'表格' –

+0

難題。如果你不使用標準表單提交按鈕類型,你不需要preventDefault 。您正在腳本中定義提交功能,因此防止默認很可能會阻止按鈕點擊註冊,而不是您預期的默認表單提交。 – Korgrue