简体   繁体   English

如何使用提交按钮和输入按钮提交值?

[英]How to submit a value with a submit button AND by the enter button?

Can someone help me with some javascript code?有人可以帮我写一些 javascript 代码吗?

I would start a javascript function after click the submit button AND after pressing the 'Enter' key.单击提交按钮和按下“Enter”键后,我将启动一个 javascript 函数。 I've made this code, seperately it works, but together the 'Enter' key doesn't works.我已经制作了这段代码,单独它可以工作,但是“Enter”键一起不起作用。 What goes wrong?出了什么问题?

Thanks!!谢谢!!

<form onsubmit="SubmitFormData(); return false;" id="myForm" method="post">

 Name:    <input name="name" id="name" type="text" /><br />


<input type="submit" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>

<script>
var input = document.getElementById("name");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   SubmitFormData();
  }
});
</script>

function SubmitFormData() {
var name = $("#name").val();
$.post("submit.php", { name: name },
function(data) {
 $('#results').html(data);
 $('#myForm')[0].reset();
});
}

Your SubmitFormData() function will work only if you click on the input button (you added the onclick attribute to it).您的SubmitFormData()函数只有在您单击input按钮时才会起作用(您向其添加了onclick属性)。

You should remove it and add the following attribute to your form : onsubmit="SubmitFormData(); return false;"您应该删除它并将以下属性添加到您的formonsubmit="SubmitFormData(); return false;"

Obs.: change your type attribute on the input.观察:更改输入上的type属性。 The type="button" it's wrong. type="button"是错误的。 Use type="submit" .使用type="submit"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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