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