我希望用户能够通过单击提交按钮或回车键来提交表单。我正在使用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>
答案 0 :(得分:0)
<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.")
}
});
答案 1 :(得分:0)
您应该使用提交类型的按钮。它不应该是文本类型。
答案 2 :(得分:0)
将整个内容包裹在form
代码中,并将按钮类型更改为submit
。然后输入将提交表格。
<form>
<input id="weather"/>
<button id="myButton" type="submit">Response</button>
</form>
答案 3 :(得分:0)
最好的方法是用表格包装输入和按钮,并在表格提交时检查输入:
$(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.")
}
});
});
&#13;
<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>
&#13;