【问题标题】:How do I determine which form is submitted and process different submission function using jquery如何确定提交哪个表单并使用 jquery 处理不同的提交功能
【发布时间】:2012-02-09 23:02:57
【问题描述】:

我是 jquery 的新手,我正在尝试更改现有的页面模板,该模板使用 jquery 作为联系表单来处理表单验证。如果表单元素有效,它会将数据元素提交到处理它的页面(发送电子邮件)。我要做的是更改现有代码,因为我在同一页面上有两个额外的表单。本质上,一个表单用于生成联系电子邮件,第二个表单包含一些用于向贝宝提交捐赠请求的元素,第三个表单将类似于联系电子邮件,但将包含一些其他表单元素以提供更多信息比标准的联系表格。

这个难题有几个部分。首先,有一个名为 script.js 的文件,其中包含以下内容:

$(document).ready(function() {
    // hover

    $('#menu> li > a strong').css({opacity:0})

    $('#menu > li').hover(function(){
        $(this).find('> a strong').stop().animate({opacity:1})             
    }, function(){
        if  (!$(this).hasClass('active')&&!$(this).hasClass('sfHover')) {
            $(this).find('> a strong').stop().animate({opacity:0})             
        }
    })

    $('.list1 .img_act').css({opacity:0, display:'none'})

    $('.list1 li').hover(function(){
        $(this).find('.img_act').css({display:'block'}).stop().animate({opacity:1}, function(){$(this).css({opacity:'none'})})                        
    }, function(){
        $(this).find('.img_act').stop().animate({opacity:0}, function(){$(this).css({display:'none'})})                       
    })

    $("a[data-type^='prettyPhoto']").prettyPhoto({animation_speed:'normal',theme:'facebook',slideshow:3000, autoplay_slideshow: false});
        $('.lightbox-image').hover(function(){
            $(this).find('.play').stop().animate({width:71, height:71, marginTop:-35, marginLeft:-35})
        }, function(){
            $(this).find('.play').stop().animate({width:51, height:51, marginTop:-25, marginLeft:-25})
        })



    $('ul#menu').superfish({
      delay:       600,
      animation:   {height:'show'},
      speed:       600,
      autoArrows:  false,
      dropShadows: false
    });

        //gallery 
    $("#gallery1").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".prev",
            mouseWheel: true,
            visible: 3,
            vertical: true,
            speed: 600,
            easing: 'easeOutCirc'
    });

    $('#gallery1 a').hover(function(){
        $(this).find('img').stop().animate({opacity:0.7})                           
    },function(){
        $(this).find('img').stop().animate({opacity:1})                         
    })


 });
$(window).load(function() { 
    //bg animate

    $('#bgStretch').bgStretch({
            align:'leftTop',
            navigs:$('#pagination').navigs()
        })
        .sImg({
            spinner:$('.spinner').css({opacity:.7}).hide()
    })

    $('#pagination li').eq(0).addClass('active');

    // scroll
    $('.scroll').cScroll({
        duration:700,
        step:63,
        trackCl:'track',
        shuttleCl:'shuttle'
    })

    // contact form
    $('#ContactForm').forms({
        ownerEmail:'#'
    })  

        // other form
    $('#OtherForm').forms({
        ownerEmail:'#'
    })  

        // contact form
    $('#DonateForm').forms({
        ownerEmail:'#'
    })  

        // contact form
    $('#JoinForm').forms({
        ownerEmail:'#'
    })  

    //content switch
    var content=$('#content'),
        nav=$('.menu');
    nav.navs({
        useHash:true
    })  
    nav.navs(function(n, _){
        content.cont_sw(n);
        $('#menu > li').not('.sfHover').find('>a strong').stop().animate({opacity:0})
        if (_.n!=-1) {
            $('#menu > li').eq(_.n).find('>a strong').stop().animate({opacity:1})
        }
        if (_.n==0) {
            $('#content').stop().animate({height:310})
        } else {
            $('#content').stop().animate({height:510})
        }
    })
    content.cont_sw({
        showFu:function(){
            var _=this          
            $.when(_.li).then(function(){
                _.next.css({display:'block', left:-1500}).stop().animate({left:0},600, function(){

                }); 
            });
        },
        hideFu:function(){
            var _=this
            _.li.stop().animate({left:2000},600, function(){
                _.li.css({display:'none'})
            })
        },
        preFu:function(){
            var _=this
            _.li.css({position:'absolute', display:'none'});
        }
    })
    nav.navs(0);

    var h_cont=950;
    function centre() {
        var h=$(window).height();
        if (h>h_cont) {
            m_top=~~(h-h_cont)/2+12;
        } else {
            m_top=12;
        }
        $('#content').stop().animate({marginTop:m_top})
    }
    centre();
    $(window).resize(centre);

})

然后有一个名为 forms.js 的单独文件,其中包含表单验证和提交的代码。这就是我正在尝试使用的方法,以便能够验证并提交我的其他两个表单。这是 forms.js 的完整代码(而不是原始帖子中的 sn-p):

    (function($){
    $.fn.extend({
        forms:function(opt){
            if(opt===undefined)
                opt={}
            this.each(function(){
                var th=$(this),
                    data=th.data('forms'),
                    _={
                        errorCl:'error',
                        emptyCl:'empty',
                        invalidCl:'invalid',
                        successCl:'success',
                        successShow:'4000',
                        mailHandlerURL:'bin/MailHandler.php',
                        ownerEmail:'support@guardlex.com',
                        stripHTML:true,
                        smtpMailServer:'localhost',
                        targets:'input,textarea',
                        controls:'a[data-type=reset],a[data-type=submit]',
                        validate:true,
                        rx:{
                            ".employer":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                            ".name":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                            ".state":{rx:/^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/,target:'input'},
                            ".email":{rx:/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,target:'input'},
                            ".phone":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},
                            ".fax":{rx:/^\+?(\d[\d\-\+\(\) ]{5,}\d$)/,target:'input'},
                            ".message":{rx:/.{20}/,target:'textarea'}
                        },
                        preFu:function(){
                            _.labels.each(function(){
                                var label=$(this),
                                    inp=$(_.targets,this),
                                    defVal=inp.attr('value'),
                                    trueVal=(function(){
                                                var tmp=inp.is('input')?(tmp=label.html().match(/value=['"](.+?)['"].+/),!!tmp&&!!tmp[1]&&tmp[1]):inp.html()
                                                return tmp
                                            })()

                                trueVal!=defVal
                                    &&inp.val(defVal=trueVal||defVal)
                                label.data({defVal:defVal})                             
                                inp
                                    .bind('focus',function(){
                                        inp.val()==defVal
                                            &&(inp.val(''),_.hideEmptyFu(label),label.removeClass(_.invalidCl))
                                    })
                                    .bind('blur',function(){
                                        !inp.val()
                                            ?inp.val(defVal)                                        
                                            :(_.isValid(label)
                                                ?_.showErrorFu(label)
                                                :_.hideErrorFu(label)),
                                            (_.isEmpty(label)
                                                ?_.showEmptyFu(label)
                                                :_.hideEmptyFu(label))
                                    })
                                    .bind('keyup',function(){
                                        label.hasClass(_.invalidCl)
                                            &&_.isValid(label)
                                                ?_.showErrorFu(label)
                                                :_.hideErrorFu(label)
                                    })
                                label.find('.'+_.errorCl+',.'+_.emptyCl).css({display:'block'}).hide()
                            })
                            _.success=$('.'+_.successCl,_.form).hide()
                        },
                        isValid:function(el){
                            var ret=true,
                                empt=_.isEmpty(el)
                            if(empt)
                                ret=false,
                                el.addClass(_.invalidCl)
                            else
                                $.each(_.rx,function(k,d){
                                    if(el.is(k))
                                        d.rx.test(el.find(d.target).val())
                                            ?(el.removeClass(_.invalidCl),ret=false)
                                            :el.addClass(_.invalidCl)
                                })
                            return ret
                        },
                        isEmpty:function(el){
                            var tmp
                            return (tmp=el.find(_.targets).val())==''||tmp==el.data('defVal')
                        },
                        validateFu:function(){                          
                            _.labels.each(function(){
                                var th=$(this)                              
                                _.isEmpty(th)
                                    ?_.showEmptyFu(th)
                                    :_.hideEmptyFu(th)
                                _.isValid(th)
                                    ?_.showErrorFu(th)
                                    :_.hideErrorFu(th)
                            })
                        },
                        submitFu:function(){
                            _.validateFu()
                            var id=$(this).attr('id');
                            var action=$(this).attr('action');

                            if(!_.form.has('.'+_.invalidCl).length)
                                $.ajax({
                                    type: "POST",
                                    url:_.mailHandlerURL,
                                    data:{
                                        name:$('.name input',_.form).val()||'nope',
                                        email:$('.email input',_.form).val()||'nope',
                                        phone:$('.phone input',_.form).val()||'nope',
                                        fax:$('.fax input',_.form).val()||'nope',
                                        state:$('.state input',_.form).val()||'nope',
                                        message:$('.message textarea',_.form).val()||'nope',
                                        owner_email:_.ownerEmail,
                                        stripHTML:_.stripHTML
                                    },
                                    success: function(){
                                        _.showFu()
                                    }
                                })          
                        },
                        showFu:function(){
                            _.success.slideDown(function(){
                                setTimeout(function(){
                                    _.success.slideUp()
                                    _.form.trigger('reset')
                                },_.successShow)
                            })
                        },
                        controlsFu:function(){
                            $(_.controls,_.form).each(function(){
                                var th=$(this)
                                th
                                    .bind('click',function(){
                                        _.form.trigger(th.data('type'))
                                        return false
                                    })
                            })
                        },
                        showErrorFu:function(label){
                            label.find('.'+_.errorCl).slideDown()
                        },
                        hideErrorFu:function(label){
                            label.find('.'+_.errorCl).slideUp()
                        },
                        showEmptyFu:function(label){
                            label.find('.'+_.emptyCl).slideDown()
                            _.hideErrorFu(label)
                        },
                        hideEmptyFu:function(label){
                            label.find('.'+_.emptyCl).slideUp()
                        },
                        init:function(){
                            _.form=this
                            _.labels=$('label',_.form)

                            _.preFu()

                            _.controlsFu()

                            _.form
                                .bind('submit',function(){
                                    if(_.validate)
                                        _.submitFu()
                                    else
                                        _.form[0].submit()
                                    return false
                                })
                                .bind('reset',function(){
                                    _.labels.removeClass(_.invalidCl)                                   
                                    _.labels.each(function(){
                                        var th=$(this)
                                        _.hideErrorFu(th)
                                        _.hideEmptyFu(th)
                                    })
                                })
                            _.form.trigger('reset')
                        }
                    }
                if(!data)
                    (typeof opt=='object'?$.extend(_,opt):_).init.call(th),
                    th.data({cScroll:_}),
                    data=_
                else
                    _=typeof opt=='object'?$.extend(data,opt):data
            })
            return this
        }
    })
})(jQuery)

其中大部分已经包含在我的页面模板中并且可以正常工作。我在 script.js 文件中为另外两个表单添加了以下内容

// Donate form
$('#DonateForm').forms({
    ownerEmail:'#'
})  

    // join form
$('#JoinForm').forms({
    ownerEmail:'#'
})  

我让他们从验证的角度工作。也就是说,他们似乎以与原始联系表格相同的方式正常行事。例如,如果您单击按钮或离开某个元素的焦点,您会收到用户反馈,表明该表单元素是必需的。但我不太清楚如何让他们提交。

在我看来,forms.js 中的原始代码是专门为提交联系表单而编写的。我的第一个想法是以某种方式在表单名称上添加一个额外的评估,每个都有它自己的 url 值和从表单中提取的一组数据值。我只是不确定如何做到这一点,这是 jquery 的新手。就目前而言,我的其他表单似乎得到了验证,但是当我点击提交按钮时没有任何反应。

【问题讨论】:

    标签: jquery ajax forms


    【解决方案1】:

    你可以更轻松地使用

    $('form').submit(function(e){
        e.preventDefault();
        var id=$(this).attr('id');
        var action=$(this).attr('action');
        if(id=='some_id')
        {
           $.ajax({
               type: "POST",
               url:action,
               data:{...},
               success: function(){...}  
           });
        }
    
        if(id=='something_else')
        {
           $.ajax({
               type: "POST",
               url:action,
               data:{...},
               success: function(){...}  
            });
        }
    });
    

    将这段代码 sn-p 放入 $(document).ready(function(){...}) 并为每个表单赋予唯一的 id。

    【讨论】:

    • 感谢您的回复。这就是我最初想到的那种事情。但是,这并不完全适合现有代码。我已经修改了原始帖子以包含我正在使用的完整代码。如果我按原样实现,恐怕我会丢失现有的有效验证代码。
    【解决方案2】:

    第一步:为您的表单命名,以便您轻松检索它们

    //example
    <form id="joebob" name="jimbob" ...
    // in jquery can be called dynamically as:
    $("#joebob")
    //or
    $("form[name=jimbob]")
    //or you can create one dnamically
    var frmJoeBob = $("<form />").attr({ id: "joebob", action: "#smartUrl" });
    

    第二步:我强烈建议你去here 并将这个插件添加到你的库中。

    • 只需在 jquery 脚本调用后下载 js 并将其添加到您的标题中。
    • 它的作用是允许以一种极其简单的方式ajaxing您的表单,这样您就可以更好地控制它们的操作和操作时间。

    示例用法

    // first establish a set of option in object style
    var formAjaxOptions = {
        target: $("#SomeOutpuEle"),  //  this is where return text will be displayed on complete
        beforeSubmit: function (formData, jqForm, options) { 
            /* Here you can preform work such as form validation before 
            the form is submitted. return false; to stop the form from 
            being submitted. */ 
        },
        success: function(responseText, statusText, xhr, $formresponseText, statusText, xhr, $form) { 
            /* Here you can preform work if the ajax call was successful, 
            this doesn't mean the serverside didn't have failures, though.  
            This simply means the ajax call is complete. console.log the 
            vars to get more information on them or see the docs.  */ 
        }
    }
    
    // then ajax your form using the plugin with these options as such:
    $("#joebob").ajaxForm(formAjaxOptions);
    
    // then simply grab anything you wanna use as a button and set a click event to submit your form
    $("span.someButtonAsaSpan").click(function(e) {
        $("#joebob").submit();
    });
    

    看看这有多容易? 还有一点需要注意的是,options 对象也可以用来(在这个插件中)提交 jQuery.ajax 选项,所以一旦你对正在发生的事情有了更多的了解,你就可以随心所欲地完全自定义它!

    【讨论】:

    • 感谢您为初学者提供参考表单名称的快速课程。如果对语言没有更好的了解,我通常不会尝试编辑已建立的代码,但我没有时间从头开始。我还将研究您引用的插件,看看我将来如何使用它。我只是希望不要完全重写现有的表单功能,所以希望能够弄清楚如何在我已有的代码范围内工作。我已将完整代码发布到原始问题中。感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    相关资源
    最近更新 更多