Javascript 按下提交按钮后更改表单值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4517366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change form values after submit button pressed
提问by Editorman
[EDIT] After a lot of digging around, I found out that the problem was in how I integrated the CKEditor into my page. The simple and obvious way doeswork in this case, as laid out in the accepted answer.
[编辑] 经过大量挖掘,我发现问题在于我如何将 CKEditor 集成到我的页面中。正如接受的答案中所述,这种简单而明显的方法在这种情况下确实有效。
Hi,
你好,
I need to change the values of a form, after the submit button has been pressed, but before the actual submission has taken place.
我需要在按下提交按钮后但在实际提交之前更改表单的值。
I've tried hooking into the "submit" event of the form, and changing the text field values there manually, but it looks like that doesn't actually change the values submitted.
我试过挂钩表单的“提交”事件,并手动更改那里的文本字段值,但看起来这实际上并没有更改提交的值。
Any ideas?
有任何想法吗?
回答by T.J. Crowder
I'm curious about your statement that the submit
handler didn't work for you. It does for me. I've used it for years to fill in hidden fields before sending forms in; should work for other form fields as well.
我很好奇你关于submit
处理程序不适合你的说法。它对我有用。多年来,我一直在使用它来填写隐藏字段,然后再发送表单;也应该适用于其他表单字段。
Example (live copy):
示例(实时复制):
HTML:
HTML:
<form id='theForm'
action='http://www.google.com/search'
method='GET' target='_new'>
<label>Search for:
<input type='text' name='q' id='txtSearch'></label>
<input type='submit' id='btnSearch' value='Search'>
JavaScript:
JavaScript:
window.onload = function() {
document.getElementById('theForm').onsubmit = function() {
var txt = document.getElementById('txtSearch');
txt.value = "updated " + txt.value;
};
};?
Tested and working on IE6 and IE7 on Windows, and Chrome, Firefox, and Opera on Linux.
在 Windows 上的 IE6 和 IE7 以及 Linux 上的 Chrome、Firefox 和 Opera 上进行了测试和工作。
Update: Based on your comment below, you're using jQuery. Works fine using jQuery for everything as well:
更新:根据您在下面的评论,您正在使用 jQuery。使用 jQuery 也可以正常工作:
$('#theForm').submit(function() {
var txt = $('#txtSearch');
txt.val("updated " + txt.val());
});
Live exampleTested and working on the same set of browsers. This versionuses a more open search rather than an id
, and also still works.
回答by lonesomeday
You need to prevent the default submit action and then resubmit the form yourself manually:
您需要阻止默认提交操作,然后自己手动重新提交表单:
$('form').submit(function(e) {
e.preventDefault();
// do your processing
this.submit(); // call the submit function on the element rather than
// the jQuery selection to avoid an infinite loop
});
回答by lonesomeday
Did you try adding function on click JavaScript event on the submit button and changing the values? It may work because client script will execute first
您是否尝试在提交按钮上的单击 JavaScript 事件上添加函数并更改值?它可能会起作用,因为客户端脚本将首先执行