簡體   English   中英

<button>單擊</button> “ <button>”</button>時提交表單

[英]Form submits when “<button>” is clicked

我有一個帳戶創建表格。 沒有提交按鈕,只有一個<button> 現在,單擊按鈕時,我正在運行jQuery驗證。 正在運行驗證,並顯示了適當的錯誤,但隨后提交了表單並重新加載了頁面。 即使我沒有提交按鈕,也沒有jQuery submit()函數。

HTML:

<form id="accountCreate" method="POST" action="<?=site_url('account/create')?>">
    <h3>Create an Account</h3>
    <ul>
        <li><input type="text" name="email" placeholder="Email..." /></li>
        <li><input type="password" name="password" placeholder="Password..." id="password" /></li>
        <li><input type="password" placeholder="Verify Password..." id="verifyPassword" /></li>
        <li><button id="button">Create</button></li>
    </ul>
</form>

JS:

$(document).ready(function() {
$('#button').click(function() { 
    var password = $('input#password').val();
    var passwordV = $('input#passwordVerify').val();

    if (password.length >= 6 && password.length <= 24) {
        if (password == passwordV) {

        } else {
            $('div#error').css('display', 'inline');
            $('div#error span.errorMessage').text('hey');
        }
    } else {
        alert('yo');
        return false;
    }
});
});

如果未定義type屬性,則<button />充當提交按鈕。
添加type="button"可以解決此問題。

<button id="button" type="button">Create</button>

http://www.w3.org/TR/html-markup/button.html#button

您需要為按鈕指定默認的type=屬性,因為不同的瀏覽器可以使用不同的默認值。 在您的情況下,瀏覽器似乎默認為type="submit"

$(document).ready(function() {
$('#button').click(function() { 
var password = $('input#password').val();
var passwordV = $('input#passwordVerify').val();

if (password.length >= 6 && password.length <= 24) {
    if (password == passwordV) {

    } else {
        $('div#error').css('display', 'inline');
        $('div#error span.errorMessage').text('hey');
    }
} else {
    alert('yo');
    return false;
}
//Just add return false
return false;
});
});

您應該添加evt.preventDefault(); 使提交只做您想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM