javascript 如何在javascript中自动提交表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7430590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to autosubmit a form in javascript?
提问by Momo
I have a form with an input text field which imports data every couple of seconds and display it in the form field , let us say :
我有一个带有输入文本字段的表单,它每隔几秒钟导入一次数据并将其显示在表单字段中,让我们说:
<input name="code" id="code" type="text" size="64" maxlength="128" />
and a submit button and my form has the formname form1. I want the submit button to be clicked as soon as the data in the form field is changed. I did try to do the following. In the header I did add the follwoing javascript:
和一个提交按钮,我的表单的表单名称为 form1。我希望在更改表单字段中的数据后立即单击提交按钮。我确实尝试执行以下操作。在标题中,我确实添加了以下 javascript:
<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>
and on the form :
并在表格上:
<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />
but it didn`t work..
但它没有用..
Any help ?
有什么帮助吗?
Thanks
谢谢
采纳答案by Philip Schweiger
Something like this would work:
像这样的事情会起作用:
<form action="#">
<input type="" id="input" />
<button type="submit"></button:>
</form>
<script>
function send_data() {
document.forms[0].submit();
}
window.onload = function(){
var input = document.getElementById('input');
input.onchange = send_data;
}
</script>
But I'd add a few caveats:
但我要补充几点:
- I'm assuming there is only one form on the page. You would be safer assigning and ID to your form and using
getElementById
and referencing that instead ofdocument.forms[x]
- The change event will only happen after you lose focus on the input, which I probably what you want? Just making sure it's expected behavior
- Without knowing why you need to do this, I'd note that it could potentially be very annoying to the user, as submission will trigger a new page load. You may be better off doing a submission via ajax so as not to disrupt the user's browsing. If you do this, I strongly recommend a JS library to handle this.
- 我假设页面上只有一个表单。你会更安全地为你的表单分配和 ID 并使用
getElementById
和引用它而不是document.forms[x]
- 更改事件只会在您失去对输入的关注后发生,这可能是您想要的?只是确保它是预期的行为
- 在不知道为什么需要这样做的情况下,我注意到这可能会让用户感到非常恼火,因为提交会触发新页面加载。您最好通过 ajax 进行提交,以免干扰用户的浏览。如果你这样做,我强烈推荐一个 JS 库来处理这个问题。