改变输入值然后在JavaScript中提交表单 [英] Change value of input then submit form in JavaScript
问题描述
我目前正在研究一个基本表单。我想用这种形式做的事情是,当你点击提交/按钮来首先改变一个字段的值,然后像平常一样提交表单。它看起来有点像这样:
I'm currently working on a basic form. What I want to do with this form is that when you hit submit/button to 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,但不提交表单。我真的是一个JavaScript noobie,所以原谅我,如果这只是一个太简单的问题,但我只是没有得到真正的窍门。
And this is how far I've come with the JavaScript. It changes "myinput"'s value to 1 but does not submit the form. I'm really a JavaScript noobie so forgive me if this is just a too simple question but I'm just not getting the hang of it really.
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事件;事件的顺序并不是很明显,如果用户通过在文本框中按回车来提交,则不会调用回调。
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屋!