2012-02-09 51 views
0

处理不同的提交功能我是新来的jQuery,我试图改变使用jQuery的联系人的形式来处理表单验证现有的页面模板。如果表单元素有效,它将数据元素提交给处理它的页面(发送电子邮件)。我想要做的是改变现有的代码,因为我有两个在同一页面上的其他表单。实质上,一种形式是用于生成联系人电子邮件,第二种形式包含用于向PayPal提交捐赠请求的几个元素,并且第三种形式将类似于联系人电子邮件,但将包含一些其他表单元素以提供更多信息比标准的联系表格。我如何确定哪种形式提交,并使用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的完整代码(而不是在原来的职位代码段):

(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:'[email protected]', 
         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的新功能。就目前而言,我的其他表单看起来会得到验证,但是当我点击提交按钮时,没有任何反应。

回答

0

步骤一:命名您的形式,所以你可以很容易地检索它们

//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这个插件添加到库中。

  • 只需下载js并将其添加到您的标头之后的jQuery脚本调用。
  • 它能做什么是允许的一个非常简单的方法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选项,所以一旦你得到了更多关于发生了什么的事情,你可以完全自定义它,不过你可以!

+0

感谢您为启动者引用表单名称的快速课程。我通常不会试图在没有更好的语言理念的情况下编辑既定的代码,但我从一开始就没有足够的时间开始。我也会看看你引用的插件,看看我将来如何使用它。我只是希望不要完全重写现有的表单功能,所以希望能够弄清楚如何在我已有的代码范围内工作。我已将完整的代码发布到原始问题。感谢您的回应! – Buzz 2012-02-10 04:04:54

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(){...} 
     }); 
    } 
}); 

将这个代码片段中的$(document)。就绪(函数(){...}),并给出一个唯一的ID给每个窗体。

+0

感谢您的回应。那是我最初想到的那种东西。但是,这并不完全适合现有的代码。我修改了原文,以包含我正在使用的完整代码。如果我按原样执行此操作,恐怕会丢失正在工作的现有验证代码。 – Buzz 2012-02-10 04:02:38

+0

不客气! – 2012-02-10 08:47:45