[英]How do I allow form submission with the submit button and the enter key?
I want the user to be able to submit a form by clicking the submit button or the enter key. 我希望用户能够通过单击“提交”按钮或Enter键来提交表单。 I'm using jQuery and here's my code:
我正在使用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"/>
The onclick script should be 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.")
}
});
You should use submit type of button. 您应该使用按钮的提交类型。 It should not be a text type.
它不能是文本类型。
Best way is to wrap input and button with form and check input only in case of form submit like: 最好的方法是用表单包装输入和按钮,并仅在表单提交时检查输入,例如:
$(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.