繁体   English   中英

Jquery表单仅在您第一次提交时工作,而不是第二次

[英]Jquery form only working the first time you submit it, and not the second

我有一个表单,您可以将数据添加到数据库。 这一切都是用jquery和ajax完成的,所以当你按下提交时它会验证代码,然后如果一切正确,它会提交帖子数据而不刷新页面。 问题是表单第一次工作,但是当你去提交另一个带有表单的条目时它不起作用。 我认为这与它有关

$(document).ready(function(){

但我真的不知道。 我已经粘贴了下面的一些代码。 它很长,但这应该提供足够的信息来了解它在做什么。 整个js文件位于http://www.myfirealert.com/callresponse/js/AddUser.js

$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect. 
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */


    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE




    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";


                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});    
});

现在,第一次使用表单时效果很好。 然后重新启用该按钮,但是当您尝试创建另一个条目并单击该按钮时,没有任何反应。

谢谢您的帮助!

编辑:表单提交后第一次按钮仍然启用,你可以点击它,但当你点击它没有任何反应...即使你没有填写表格。 就像表单的click事件第一次没有触发一样。

EDIT2根据要求,我将发布HTML,它位于受密码保护的网站后面,因此我无法向您发送页面链接。

<form action='addcallers.php' method='post' id='AddCaller_form'>

 <h2>Add Callers</h2>
 <p>
 First Name:
 <div id='Firstname_error' class='error'> Please Enter a First Name</div>
 <div><input type='text' name='Firstname' id='Firstname'></div>
 </p>

 <p>
 Last Name:
 <div id='Lastname_error' class='error'> Please Enter a Last Name</div>
 <div><input type='text' name='Lastname' id='Lastname'></div>
 </p>
 ...MORE FORM FIELDS HERE


 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 </div>
 </p>

 <p>




 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 <p id='cf_submit_p'>
 <input type='submit' id='AddCaller' value='Send The Message'>
 </p>
 </form>  

 </div>

EDIT3页面上还有其他ajax,但它是用直接的javascript编写的。 我不确定这是否会以任何方式影响功能。 但如果需要,我也可以发布那个ajax。

EDIT4我从http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/获得了原始教程并对其进行了修改

编辑在发出一些不同的警报后,我发现它不会做条件语句if(error==false)...任何想法为什么?

最有可能的是,它是#DefaultLocation字段,因为它是只读的,你在第一篇文章之后重置它:

document.getElementById('DefaultLocation').value = "";

并且永远不会将它的价值改回某些东西(或者是你?)所以你必须做以下其中一项:

  1. 不要重置它
  2. 在摆出表格后用东西设定它的价值
  3. 不要验证它,因为它只是一个只读,你用它作为一个隐藏的输入(顺便说一句是错的)!

另外,它可能是你正在谈论的其他“ajax”代码,所以请在这里发布,也许你在页面上的其他地方(元素)有相同的ID,如表格中的那些..

无论如何,这里有一些提示:1-正确关闭输入标签(添加/到它的末尾):

<input type='text' name='Firstname' id='Firstname' />

2-确保所有DIV和P都关闭......因为看起来你有一个开放的P:

 <p>


 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 </p> <---- missing this one
 <p id='cf_submit_p'>

3-您一直在重新声明错误变量,您不需要这样做:

if(Firstname.length == 0){
    var error = true;
....

只需使用error = true; 如果没有var,这适用于所有正在更改其值的地方,只在初始化时使用var

var error = false;

4-而不是这个:

$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

使用:

$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });

5-如果您使用DefaultLocation作为隐藏字段,则代替此:

 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly />

 </div>

使用:

<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />

尝试从使用单击事件处理程序更改为表单的提交事件处理程序

改变这个: $('#AddCaller').click

对此: $('#AddCaller_form').submit

不要删除disabled的属性,将其设置为false。

这条线

$('#AddCaller').removeAttr('disabled').attr(...

应该

$('#AddCaller').attr('disabled', false).attr(...

我假设通过删除和添加属性,元素被删除并替换为新元素,但处理程序不会重新附加。 尝试使用$('#AddCaller').live('click', function(){ //code })而不是.click()

此函数向php发送查询,并可以使用ajax从php文件返回结果。 我留下了评论指南。 第一部分使用try&catch语句不需要修改。 转到#1和#2

 function ajaxFunction(){
        var ajaxRequest;  


        //Browser compatible. keep it as it is 
        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        //Browser compatible end



        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                   //#2 opional: create functions to return data from your php file
                   $('#resultArea').html(ajaxRequest.responseText);
            }
        }

        //#1 Set the form method, filename & query here here
        ajaxRequest.open("GET", "serverTime.php?query=something", true);
        ajaxRequest.send(null); 
    }



例:

<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />

快速jquery插件,因为你几乎可以在你的网站上的每个ajax表单中使用它:

它将禁用所有可能触发提交事件的字段,并在表单标记上添加一个类,以便您可以应用某些样式,或在提交表单时显示加载消息:

jQuery.extend(jQuery.fn, {
  formToggle: function (enable){
    return this.each(function(){
      jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
      .find(':input').attr('disabled', !enable);
  },
  enable: function(){ return this.formToggle(true); },
  disable: function(){ return this.formToggle(false); }
}

然后在你的jq ajax代码:

[...]

var $form = $(your_form).submit(function(){
  $.ajax({
    type: 'post', 
    url: "/whatever/", 
    data: $form.serialize(), 
    success: function (){ alert ('yay');},
    complete: function(){ $form.enable();},
    error: function(){ alert('insert coin')}
  }
  $form.disable(); 
  return false;
});

在表单发送/接收数据时,应该足以正确阻止提交。 如果你真的是偏执狂,你可以添加一个检查,以便在用户触发提交和字段被禁用之间不能发送两次:if($ form.is('。disabled'))return false; 作为提交处理程序的第一行,但它确实不是必需的

在Firebug中设置一些断点并观察它是否在某处。 提交和应用效果后,按钮可能会丢失其单击处理程序。 您可能需要在提交和填充后再次分配单击处理程序。

不是100%,但尝试将代码设置为单独的函数,然后在最后重新绑定click事件。

例:

function addCaller(e) {
    // your unchanged code
    $('#AddCaller').click(addCaller(e));
}

$(document).ready(function(){
    // added an unbind just in case
    $('#AddCaller').unbind('click').click(addCaller(e));
});

尝试改变这个: $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' }); 进入: $('#AddCaller').attr({'value' : 'Adding...' });

这应该使它工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM