Change form values after submit button pressed

我的未来我决定 提交于 2019-11-26 07:43:24

问题


[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 does work in this case, as laid out in the accepted answer.

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?


回答1:


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.

Example (live copy):

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:

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.


Update: Based on your comment below, you're using jQuery. Works fine using jQuery for everything as well:

$('#theForm').submit(function() {
  var txt = $('#txtSearch');
  txt.val("updated " + txt.val());
});

Live example Tested and working on the same set of browsers. This version uses a more open search rather than an id, and also still works.




回答2:


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
});



回答3:


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



来源:https://stackoverflow.com/questions/4517366/change-form-values-after-submit-button-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!