更改输入值并在JavaScript中提交表单 [英] Change value of input and submit form in 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();
}
推荐答案
您可以改为执行以下操作:
You could do something like this instead:
<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事件;事件的顺序不是立即显而易见的,并且如果用户提交(例如,在文本框中单击return),则不会调用您的回调.
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屋!