[英]jQuery Click event not working with Submit button in a form
我有兩個要提交的按鈕,我想在單擊(提交)時禁用button2,並且當用戶單擊button1時,button2將啟用。 對不起,愚蠢的問題,我是新手。
$(document).ready(function(){ $(document).on("click", ".test2", function() { if ($('#test2').is(':visible')) { $('#test2').hide(); } else { $('#test2').show(); }; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="test" method="post"> <input id="test" type="submit" value="button1" class="test1"> <input id="test2" type="submit" value="button2"/> </form>
更改
$(document).on("click", ".test2", function() {
至
$(document).on("click", "#test2", function() {
一旦按鈕隱藏,它將不可見,因為您在要隱藏的同一按鈕上使用click事件,因此在這種情況下, 其他按鈕將無用。
當您提交表單並再次返回此表單/頁面時,按鈕將對您可見。
我不清楚您要做什么:
如果您不想提交表單,並且想要執行更多操作,則可以使用:
e.preventDefault();
按照@Nitheesh的建議並使其display:none
或disabled
Clicke事件在課程中被競標,將其更改為ID
$(document).on("click", "#test2", function()
這是示例代碼。
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $(document).on("click", "#test2", function (e) { if ($('#test2').is(':visible')) { $('#test2').hide(); e.preventDefault(); } else { $('#test2').show(); e.preventDefault(); }; }); }); </script> </head> <body> <form id="test" method="post"> <input id="test" type="submit" value="button1" class="test1"> <input id="test2" type="submit" value="button2" /> </form> </body> </html>
這個怎么樣? 將disabled
添加到#test2
,並在單擊#test
時將其刪除。
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#test").on("click", function () { $("#test2").prop("disabled",false); }); }); </script> </head> <body> <form id="test" method="post"> <input id="test" type="button" value="button1" class="test1"> <input id="test2" type="button" value="button2" disabled /> </form> </body> </html>
我會稍微改變js和html。
為什么? 原因是,如果您想在提交時禁用button2並在單擊button1時啟用它,最好不要在form
放置兩個提交。 我們放置了一個Submit button
,以觸發form
提交,並放置了一個<a>
標記以啟用button2( <a>
標記將不會再次觸發Submit事件)。
<form id="test" method="post">
<a id="test1" href="#" class="btn btn-primary">button1</a>
<button id="test2" type="submit" class="btn btn-primary">button2</button>
</form>
在jQuery中,我們在$(document).ready()
函數中執行以下操作:
$('#test').on('submit', formSubmit);
$('#test1').on('click', unableButton);
function formSubmit () {
$('#test2').prop('disabled', true);
// Here you put the rules to submit your form
}
function unableButton (e) {
e.preventDefault();
$('#test2').prop('disabled', false);
}
如果您想讓我擺弄小提琴,那么您可以查看運行中的代碼: https : //jsfiddle.net/dobbinx3/Lu2ns80b/1/
Cya。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.