如何在 JavaScript 中自动提交表单?

发布于 2024-12-04 14:45:10 字数 560 浏览 1 评论 0原文

我有一个带有输入文本字段的表单,每隔几秒导入一次数据并将其显示在表单字段中,让我们说:

<input name="code" id="code" type="text" size="64" maxlength="128" />

和一个提交按钮,我的表单的表单名称为 form1。 我希望表单字段中的数据更改后立即单击提交按钮。 我确实尝试执行以下操作。在标题中,我确实添加了以下 javascript:

<SCRIPT LANGUAGE="javascript">
function send_data()
{
document.form1.submit();
}
</SCRIPT>

和表单:

<input name="code" id="code" type="text" size="64" maxlength="128" onchange="send_data();" />

但它不起作用..

有什么帮助吗?

谢谢

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:

<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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一口甜 2024-12-11 14:45:10

像这样的东西会起作用:

<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>

但我要添加一些警告:

  1. 我假设页面上只有一种表单。您会更安全地为表单分配 ID 并使用 getElementById 并引用该表单,而不是 document.forms[x]
  2. 更改事件仅在您失去对表单的焦点后才会发生输入,我大概就是你想要的?只是确保它是预期的行为
  3. 在不知道为什么需要这样做的情况下,我注意到这可能会让用户非常烦人,因为提交将触发新页面加载。您最好通过 ajax 进行提交,以免干扰用户的浏览。如果你这样做,我强烈推荐一个 JS 库来处理这个问题。

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:

  1. 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 of document.forms[x]
  2. 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
  3. 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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文