在 JavaScript 中更改输入和提交表单的值 [英] Change value of input and submit form in JavaScript

查看:40
本文介绍了在 JavaScript 中更改输入和提交表单的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个基本表格.当你点击提交按钮时,它应该首先改变一个字段的值,然后像往常一样提交表单.这一切看起来有点像这样:

I'm currently working on a basic form. When you hit the submit button, it should first change the value of a field, and then submit the form as usual. It all looks a bit like this:

<form name="myform" id="myform" action="action.php">
    <input type="hidden" name="myinput" value="0" />
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" onclick="DoSubmit()" />
</form>

这就是我使用 JavaScript 代码的程度.它将myinput"的值更改为 1,但不提交表单.

And this is how far I've come with the JavaScript code. It changes "myinput"'s value to 1, but it does not submit the form.

function DoSubmit(){
  document.myform.myinput.value = '1';
  document.getElementById("myform").submit();
}

推荐答案

你可以这样做:

<form name="myform" action="action.php" onsubmit="DoSubmit();">
    <input type="hidden" name="myinput" value="0" />
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" />
</form>

然后修改你的 DoSubmit 函数,使其返回 true,表示没关系,现在你可以提交表单了";到浏览器:

And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:

function DoSubmit(){
  document.myform.myinput.value = '1';
  return true;
}

我也对在提交按钮上使用 onclick 事件持谨慎态度;事件的顺序不是很明显,如果用户提交,例如,在文本框中点击返回,则不会调用您的回调.

I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.

这篇关于在 JavaScript 中更改输入和提交表单的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆