Rob*_*Rob 0 html javascript php onclick onsubmit
我想同时执行onclick和onsubmit,这可能吗?或者,如果这是不好的做法,我如何合并这两个代码来执行这两个事件?
我有这段代码检查表单标记上的必填字段:
onsubmit="return formCheck(this);"
Run Code Online (Sandbox Code Playgroud)
然后我在相同表单的提交按钮上有这段代码:
onClick="jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,单击提交按钮时,它完全忽略了提交代码.我怎样才能将它们合并在一起?
更新我希望它首先检查必填字段,然后发送表格,如果一切正常.
更新:我在这里粘贴了整个代码,我真的很挣扎,因为这是由以前的开发人员完成的.如果有人可以将解决方案放入代码中,那就太棒了.我会奖励.
Jas*_*per 12
将onClick代码放在与onSumbit代码相同的函数中.
UPDATE
在您的onClick代码结束时return false;,这将停止事件的正常传播并停止onSubmit事件触发.因此,如果您希望提交按钮提交表单,请return false;从其onClick处理程序中删除.
当您单击提交按钮时,您将触发click按钮上的submit事件以及嵌套按钮的表单上的事件(除非您停止使用类似的事件传播事件return false;).
所以你真的只需要一个submit事件处理程序来完成两个当前处理程序的工作.
此外,由于您的页面中包含jQuery Core,您可以附加如下事件处理程序:
$(function () {
$('#form-id').on('submit', function () {
var $this = $(this);//$this refers to the form that is being submitted
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + $this.find('#name').val() + '&country=' + $this.find('#country').val() + '&email=' + $this.find('#email').val() + '&department=' + $this.find('#department').val()
});
//now we run your normal onSubmit code and return it's return value of this event handler
return formCheck(this);
});
});
Run Code Online (Sandbox Code Playgroud)
如果要将整个表单发送到jQuery.facebox函数,那么可以使用jQuery的.serialize()函数来创建必要的查询字符串:
$(function () {
$('#form-id').on('submit', function () {
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
return formCheck(this);
});
});
Run Code Online (Sandbox Code Playgroud)
这是一个演示:http://jsfiddle.net/vAFfj/
文档.serialize():http://api.jquery.com/serialize
请注意,这.on()是jQuery 1.7中的新增功能,在这种情况下.bind()与旧版本相同.
UPDATE
如果要formCheck()在运行facebox插件之前检查函数的返回值,则可以执行以下操作:
$(function () {
$('#form-id').on('submit', function () {
//check if the form data is valid
if (formCheck(this) === true) {
//if the form data is valid then run the facebox plugin
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
//also return true to stop running this function
return true;
}
//if the form data is not valid then return false to stop the submission of the form
return false;
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9123 次 |
| 最近记录: |