javascript 是否可以在发送之前更改表单数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7730625/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:06:22  来源:igfitidea点击:

Is it possible to change form data before sending it?

javascriptjqueryforms

提问by Ivan

I'd like to find any generic method to change data before sending forms. It is, if I have a <form>that contains a <input>of certain type (class) and user press sendbutton, I'd like to transform this input value to another format so it arrive to server in a corrected format.

我想在发送表单之前找到任何通用方法来更改数据。<form>也就是说,如果我有一个包含<input>某种类型(类)的并且用户按下发送按钮,我想将此输入值转换为另一种格式,以便它以正确的格式到达服务器。

I know I can set a submit()handler to process data, but I need a generic solution that setup this mechanism on load on all page forms and forgets about it (perhaps some forms are sent by AJAX, other use Jquery.validate to send, etc)

我知道我可以设置一个submit()处理程序来处理数据,但是我需要一个通用的解决方案来在所有页面表单上设置这个机制并忘记它(也许一些表单是由 AJAX 发送的,其他使用 Jquery.validate 发送, 等等)

回答by airportyh

Use jQuery's to select all form elements: $('form')and register a handler for the form submitevent. Something like this:

使用 jQuery 选择所有表单元素:$('form')并为表单submit事件注册一个处理程序。像这样的东西:

$('form').submit(function(e){
    e.preventDefault()
    var $this = $(this)
    var formData = $this.serialize()
    // do some thing to it
    var yourData = transform(formData)
    $.ajax({
       post: $this.attr('action'),
       data: yourData,
       ...
    })
})

References

参考

回答by mplungjan

Perhaps this

也许这

$(document).ready(function() {
  $("form").on("submit",function() {
    var form = $(this);
    var field = form.find("input[name=first_name]");
    if (field.length()>0) field.val(field.val().replace("a","b")); 
  });
});

回答by rapadura

Yes, why not?

是的,为什么不?

Have an onclick on the form submit button and there you can do whatever you like before you invoke submit(). To add a same function to all input type submit, then iterate over all input elements with the type=buttons and add your onclick handler function to it.

在表单提交按钮上单击一次,然后您可以在调用 submit() 之前执行任何您喜欢的操作。要将相同的函数添加到所有输入类型提交,然后使用 type=buttons 迭代所有输入元素并将您的 onclick 处理函数添加到其中。

All your forms need to be of the same kind, or if some use input type=submit while others use a button element with your own javascript then you will have to adjust for that.

您的所有表单都需要是同一类型的,或者如果有些表单使用 input type=submit 而其他表单使用带有您自己的 javascript 的按钮元素,那么您将不得不为此进行调整。