[英]How do I allow form submission with the submit button and the enter key?
我希望用戶能夠通過單擊“提交”按鈕或Enter鍵來提交表單。 我正在使用jQuery,這是我的代碼:
<input id="weather"/>
<button id="myButton" type="text">Response</button>
</div>
<script type="text/JavaScript">
$("#myButton").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#myButton").submit();
}
});
document.getElementById("myButton").onclick = function() {
if (document.getElementById("weather").value.toLowerCase() != "nice" && document.getElementById("weather").value.toLowerCase() != "crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
} else if (document.getElementById("weather").value.toLowerCase() == "nice") {
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
};
</script>
<input type="text" id="weather" />
<input type="button" id="myButton" value="Response"/>
onclick腳本應為
document.getElementById("myButton").onclick(function(){
if (document.getElementById("weather").value.toLowerCase() !="nice" && document.getElementById("weather").value.toLowerCase() !="crappy") {
alert("Please enter only either 'Nice' or 'Crappy.'");
}
else if (document.getElementById("weather").value.toLowerCase() =="nice"){
alert("GREAT! Let's go the the BEACH!!");
} else {
alert("Hmm. That blows. Well then, I just won't be going outside today.")
}
});
您應該使用按鈕的提交類型。 它不能是文本類型。
將整個內容包裝在一個form
標簽中,然后將按鈕類型更改為submit
。 輸入,然后提交表格。
<form>
<input id="weather"/>
<button id="myButton" type="submit">Response</button>
</form>
最好的方法是用表單包裝輸入和按鈕,並僅在表單提交時檢查輸入,例如:
$(function() { $("#weatherForm").submit(function(event) { event.preventDefault(); var $weatherElement = $('#weather'); if ($weatherElement.val() != "Nice" && $weatherElement.val() != "Crappy") { alert("Please enter only either 'Nice' or 'Crappy.'"); } else if ($weatherElement.val() == "Nice") { alert("GREAT! Let's go the the BEACH!!"); } else { alert("Hmm. That blows. Well then, I just won't be going outside today.") } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="#" id="weatherForm"> <input id="weather" name="weather" /> <input type="submit" id="myButton" value="Response" /> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.