多个联系表单在同一页面jQuery上

时间:2014-10-25 12:27:47

标签: php jquery html forms contact

我有TMForm.js和MailHandler.php的联系表格,效果很好。

现在我想在同一个html页面上添加另一个联系表单,我想在电子邮件中识别我将从提交中收到的第二个表单。

问题是仅适用于第一种形式。我该如何解决这个问题?

这是我的代码: HTML:

         <form id="contact-form" method="post" action="bat/MailHandler.php">
                  <div class="success_wrapper">
                    <div class="success-message">Il messaggio è stato inviato
                      con successo. Sarai contattato al più presto.</div>
                  </div>
                  <label class="name"> <input placeholder="Nome*:" data-constraints="@Required @JustLetters"

                      type="text"> <span class="empty-message">*Questo campo è
                      obbligatorio.</span> <span class="error-message">*Nome
                      non valido. Inserisci un nome valido.</span> </label> 
                      <label class="email"> <input placeholder="E-mail*:" data-constraints="@Required @Email"

                      type="text"> <span class="empty-message">*Questo campo è
                      obbligatorio.</span> <span class="error-message">*E-mail
                      non valido. Inserisci un e-mail valido.</span> </label> <label

                    class="phone"> <input placeholder="Telefono:" data-constraints="@Required @JustNumbers"

                      type="text"> <span class="empty-message">*Questo campo è
                      obbligatorio.</span> <span class="error-message">*Numero
                      di telefono non valido. Inserisci un numero valido</span>
                  </label> <label class="message"> <textarea placeholder="Messaggio*:"

                      data-constraints="@Required @Length(min=20,max=999999)" style="height: 72px"></textarea>
                    <span class="empty-message">*Questo campo è obbligatorio.</span>
                    <span class="error-message">*Il messaggio è troppo corto.</span>
                  </label>
                  <div>
                    <div class="btn"> <a class="def-btn btn1" href="#" data-type="submit">INVIA
                        RICHIESTA</a>
                      <p class="fields">*Campi
 obbligatori</p>
                    </div>
                  </div>
                </form>

这是TMform.js:

//TMForm
(function($){
        $.fn.TMForm=function(opt){
                return this.each(TMForm)

                function TMForm(){
                        var form=$(this)
                        opt=$.extend({                                  
                                        okClass:'ok'
                                        ,emptyClass:'empty'
                                        ,invalidClass:'invalid'
                                        ,successClass:'success'
                                        ,onceVerifiedClass:'once-verified'
                                        ,mailHandlerURL:'bat/MailHandler.php'                                   
                                        ,successShowDelay:'20000'
                                        ,stripHTML:true
                                },opt)

                        init()

                        function init(){                                
                                form
                                        .on('submit',formSubmit)
                                        .on('reset',formReset)
                                        .on('focus','[data-constraints]',function(){
                                                $(this).parents('label').removeClass(opt.emptyClass)
                                        })
                                        .on('blur','[data-constraints]:not(.once-verified)',function(){
                                                $(this)
                                                        .addClass(opt.onceVerifiedClass)
                                                        .trigger('validate.form')
                                        })
                                        .on('keyup','[data-constraints].once-verified',function(){                                              
                                                $(this).trigger('validate.form')
                                        })                                      

                                if($('[data-constraints]',form).length!==0)
                                        $('[data-constraints]',form)
                                                .regula('bind')
                                                .on('show.placeholder',function(){
                                                        fieldDesolation($(this))
                                                })
                                                .on('validate.form',fieldValidate)


                                $('[placeholder]',form).TMPlaceholder()

                                $('[data-type=submit]',form)
                                        .click(function(){                                              
                                                form.trigger('submit')
                                                return false
                                        })

                                $('[data-type=reset]',form)
                                        .click(function(){                                              
                                                form.trigger('reset')
                                                return false
                                        })
                        }

                        function fieldValidate(el){
                                var el=$(this)
                                        ,result=el.regula('validate')
                                        ,isEmpty=false
                                        ,isInvalid=false
                                        ,isRequired=!!~el.data('constraints').indexOf('@Required')

                                $.each(result,function(){
                                        if(this.constraintName==='Required')
                                                isEmpty=true
                                        else
                                                isInvalid=true
                                })

                                if(!el.hasClass(opt.onceVerifiedClass)&&!isEmpty)
                                        el.addClass(opt.onceVerifiedClass)

                                if(isEmpty)
                                        el.parents('label').addClass(opt.emptyClass)

                                if(isInvalid&&!isEmpty&&isRequired)
                                        el.parents('label')
                                                .removeClass(opt.emptyClass)
                                                .removeClass(opt.okClass)
                                                .addClass(opt.invalidClass)

                                if(isInvalid&&!isRequired&&el.val())
                                        el.parents('label')
                                        .removeClass(opt.emptyClass)
                                        .removeClass(opt.okClass)
                                        .addClass(opt.invalidClass)

                                if(!result.length)
                                        el.parents('label')
                                                .removeClass(opt.invalidClass)
                                                .removeClass(opt.emptyClass)
                                                .addClass(opt.okClass)
                        }

                        function fieldDesolation(el){
                                el
                                        .removeClass(opt.onceVerifiedClass)
                                        .parents('label')
                                                .removeClass(opt.invalidClass)
                                                .removeClass(opt.emptyClass)
                                                .removeClass(opt.okClass)
                        }

                        function getValue(el){
                                return el.val()||false
                        }

                        function formSubmit(){
                                $('[data-constraints]',form).trigger('validate.form')

                                if(!$('label.'+opt.invalidClass+',label.'+opt.emptyClass,form).length){                                 
                                        $.ajax({
                                                type:"POST"
                                                ,url:opt.mailHandlerURL
                                                ,data:{
                                                        name:getValue($('label.name input'))
                                                        ,email:getValue($('label.email input'))
                                                        ,phone:getValue($('label.phone input'))
                                                        ,fax:getValue($('label.fax input'))
                                                        ,state:getValue($('label.state input'))
                                                        ,message:getValue($('label.message textarea'))
                                                        ,owner_email:opt.ownerEmail||'myemail@gmail.com'
                                                        ,stripHTML:opt.stripHTML
                                                }
                                                ,success: function(e){                                                  
                                                        form.addClass(opt.successClass)
                                                        setTimeout(function(){
                                                                form
                                                                .removeClass(opt.successClass)
                                                                .trigger('reset')
                                                        },opt.successShowDelay)
                                                }
                                        })                                      
                                }                               
                                return false
                        }

                        function formReset(){
                                fieldDesolation($('[data-constraints]',form))                                   
                        }
                }
        }       
})(jQuery)

;(function($){
        $.fn.TMPlaceholder=function(opt){
                return this.each(function(){
                        var th=$(this)
                                ,placeholder_text
                                ,placeholder

                        opt=$.extend({
                                        placeholderClass:'_placeholder'
                                        ,placeholderFocusedClass:'focused'
                                        ,placeholderHiddenClass:'hidden'
                                },opt)

                        init()

                        function init(){
                                placeholder_text=th.attr('placeholder')
                                placeholder=$(document.createElement('span'))
                                placeholder
                                        .addClass(opt.placeholderClass)
                                        .css({                          
                                                left:th.prop('offsetLeft')
                                                ,top:th.prop('offsetTop')
                                                ,width:th.width()
                                                ,height:th.outerHeight()                                
                                        })
                                        .text(placeholder_text)
                                        .appendTo(th.parent())                          
                                        .click(function(){
                                                th.focus()
                                                return false
                                        })
                                        .on('contextmenu',function(){                                           
                                                th.trigger('hide.placeholder').focus()                                          
                                        })

                                th
                                        .val('')
                                        .removeAttr('placeholder')
                                        .on('hide.placeholder',function(){
                                                placeholder.addClass(opt.placeholderHiddenClass)
                                        })
                                        .on('show.placeholder',function(){
                                                placeholder.removeClass(opt.placeholderHiddenClass)
                                        })
                                        .on('focus',function(){
                                                placeholder.addClass(opt.placeholderFocusedClass)
                                        })
                                        .on('blur',function(){
                                                var val=th.val()
                                                if(val===''||val===placeholder_text)
                                                        th.val('')                                                      
                                                        ,th.trigger('show.placeholder')
                                                placeholder.removeClass(opt.placeholderFocusedClass)
                                        })
                                        .on('keydown',function(e){                                                                                              
                                                if(e.keyCode===32||e.keyCode>46)
                                                        th.trigger('hide.placeholder')                                                  
                                        })
                                        .on('keyup',function(){                                         
                                                if(th.val()===''){                                                      
                                                        th.trigger('show.placeholder')
                                                        return false
                                                }else{                                                  
                                                        th.trigger('hide.placeholder')
                                                }
                                        })
                                        .parents('form').on('reset',function(){
                                                th.trigger('show.placeholder')                                          
                                        })
                        }                       
                })
        }
})(jQuery)
//using suggested jQuery practice by passing jQuery into a function
//in order to have $ notation without conflicting with other libraries
//Author: Troy Ingram



//HERE WAS SOME VALIDATION CODE THAT I CANCELLED IN THIS PAGE

regula.custom({
        name:'JustLetters'
        ,validator:function(){
                return /^[a-zA-Z'][a-zA-Z-' ]+[a-zA-Z']?$/.test(this.value)
        }
})
regula.custom({
        name:'JustNumbers'
        ,validator:function(){
                return /^\+?(\d[\d\-\+\(\) ]{5,}\d$)/.test(this.value)
        }
})
$(window).load(function(){
        $('#contact-form').TMForm({
           ownerEmail:'myemail@gmail.com' 
        })



    })

这是PHP:

<?php
        $owner_email = $_POST["owner_email"];
        $headers = 'From:' . $_POST["email"] . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'Content-Type: text/plain; charset=UTF-8' . "\r\n";
        $subject = 'NEW MESSAGE ' . $_POST["name"];
        $messageBody = "";

        if($_POST['name']!='nope'){
                $messageBody .= '<p>Nome: ' . $_POST["name"] . '</p>' . "\n";
                $messageBody .= '<br>' . "\n";
        }
        if($_POST['email']!='nope'){
                $messageBody .= '<p>Email Address: ' . $_POST['email'] . '</p>' . "\n";
                $messageBody .= '<br>' . "\n";
        }else{
                $headers = '';
        }
        if($_POST['state']!='nope'){            
                $messageBody .= '<p>State: ' . $_POST['state'] . '</p>' . "\n";
                $messageBody .= '<br>' . "\n";
        }
        if($_POST['phone']!='nope'){            
                $messageBody .= '<p>Phone Number: ' . $_POST['phone'] . '</p>' . "\n";
                $messageBody .= '<br>' . "\n";
        }       
        if($_POST['fax']!='nope'){              
                $messageBody .= '<p>Fax Number: ' . $_POST['fax'] . '</p>' . "\n";
                $messageBody .= '<br>' . "\n";
        }
        if($_POST['message']!='nope'){
                $messageBody .= '<p>Message: ' . $_POST['message'] . '</p>' . "\n";
        }

        if($_POST["stripHTML"] == 'true'){
                $messageBody = strip_tags($messageBody);
        }

        try{
                if(!mail($owner_email, $subject, $messageBody, $headers)){
                        throw new Exception('mail failed');
                }else{
                        echo 'mail sent';
                }
        }catch(Exception $e){
                echo $e->getMessage() ."\n";
        }
?>

2 个答案:

答案 0 :(得分:1)

对于形式1的SUBMIT Btn - &gt;使用

name="formFirst"

对于形式为2的SUBMIT Btn - &gt;使用

name="formSecond"

在PHP代码中检查

if(isset($_POST['formFirst'])){
//Your code for  1st Form submit.
}
else if (isset($_POST['formSecond'])){
//Your code for 2nd
}

答案 1 :(得分:0)

使用TMForm,您需要为每个表单指定一个唯一ID(通过更改HTML中的<form id="form">行,为第一个表单添加<form id="form1">,为第二个表单添加<form id="form2">然后,您需要告诉TMForm查找这两个ID。

为此,请一直到TMForm.js文件的底部并替换

$(window).load(function(){
  $('#form').TMForm({
      ownerEmail:'#' 
  })
})

$(window).load(function(){
  $('#form1').TMForm({
      ownerEmail:'#' 
  })
})

$(window).load(function(){
  $('#form2').TMForm({
      ownerEmail:'#' 
  })
})

您没有发布任何CSS,但如果您使用的模板类似于我所做的模板,您可能会发现现在您在页面上显示的内容有问题。这是因为form.css几乎所有东西都使用了#form,你只是将这个ID改为两个不同的东西。

我找到的最简单的解决方案是查找 - 并使用.tmform替换css文件中#form的所有实例

然后,在您的HTML中,让您的ID看起来像这样:

<form id="form" class="tmform">