我有一个插件使用jQuery,它修改了一个输入,当它被模糊时给它一个格式化遮罩,但是我不想在提交表单时通过格式化值发送。截取表单通过表单提交?
有没有一种方法可以拦截父表单提交事件,调整元素的值以删除掩码,然后继续提交而无需为每个使用插件输入的表单继续提交?
当然其他选项是使用隐藏输入并在其中存储原始值,并使用未命名的输入来显示掩码,但是如果可以的话,我想避免额外的标记(加上它将是一个方便的把戏!)
我有一个插件使用jQuery,它修改了一个输入,当它被模糊时给它一个格式化遮罩,但是我不想在提交表单时通过格式化值发送。截取表单通过表单提交?
有没有一种方法可以拦截父表单提交事件,调整元素的值以删除掩码,然后继续提交而无需为每个使用插件输入的表单继续提交?
当然其他选项是使用隐藏输入并在其中存储原始值,并使用未命名的输入来显示掩码,但是如果可以的话,我想避免额外的标记(加上它将是一个方便的把戏!)
$("#formid").submit(function(e){
e.preventDefault(); //prevent the form from submitting
var formatted_string = $("#formatted_input"); // get the formatted string you want to unformat
var unformatted_string = formatted_string.replace(/regularexpression or string to be replaced/,'replacement string'); // use .replace() function to find and replace either a string or regular expression to undo your previous formatting
$("#formatted_input").val(unformatted_string); // set the input value as the new unformatted value
$(this).submit(); //submit this form
});
您可以使用窗体的onsubmit
事件。
这个事件拦截表单提交事件,让你操纵你的数据,甚至决定是否提交表单(通过它的返回码)。
一种常见的情况是验证:
<script type="text/javascript">
function ValidateInput() {
//validate something here
return true; //true will submit the form, false will stop the submission here
}
</script>
<form action="yourfile.html" onsubmit="return ValidateInput();">
...
</form>
您可以轻松地适应这个以操纵数据。
这是可能的。问题是确保你的处理程序会在任何其他用户绑定的处理程序之前触发,例如一个阻止默认表单提交并通过Ajax完成的处理程序。 –
可能是一个相关的问题:http://stackoverflow.com/questions/2647861/modify-post-vars-before-post-using-jquery – keaukraine
你可以防止提交按钮的默认值,重新格式化字段,然后提交表单使用javascript或按照原样发送表单,并删除用于处理提交的任何格式。你需要在提交表单前完成它吗? –