繁体   English   中英

如何允许使用“提交”按钮和Enter键提交表单?

[英]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>

JSFiddle

最好的方法是用表单包装输入和按钮,并仅在表单提交时检查输入,例如:

 $(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM