开发者

Validate and submit a form without enter in an infinite cycle?

I am having an infinite cycle using this jquery code, I know WHY but I dont know HOW to fix this:

<form id="submitme">
  <input value="" name="n1" id="n1" type="text"/>
  <input value="Send" type="button"/> 
</form>
<script>
  $('#submitme开发者_开发问答').bind( 'submit', function() {
       $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
             if (data == "true")
                $('#submitme').submit();
       }); 
  });
</script>


The jQuery.validate plugin takes care of this and I would strongly recommend you using it:

$('#submitme').validate({
    rules: {
        n1: {
            remote: {
                url: 'validate.php',
                type: 'post'
            }
        }
    }
});

But if you don't want to use it another possibility is to use a global variable, like so:

$('#submitme').submit(function() {
    if (!$.formSubmitting) {
        var $form = $(this);
        $.post('validate.php', { value: $('#n1').val() }, function (data) {
            if (data == 'true') { 
                // set the global variable to true so that we don't enter
                // the infinite loop and directly submit the form
                $.formSubmitting = true;
                $form.submit();
            }
        }); 
        return false;
    }

    return true;                     
});

Just a remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:

<input value="Send" type="submit" /> 


I am not a jQuery expert, but in Prototype, when you write an event handler for an action and you don't stop the default action, than it will be executed after all of your callback functionality was done. So by simply flipping the if-else statement you should be able to avoid a infinite loop:

$('#submitme').bind( 'submit', function(event) {
    $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
    if (data != "true")
        // if validation has failed, prevent default action (submit)
        event.preventDefault();
    });
    // if default action was not prevented it will be executed
})


I found this solution:

<form id="submitme">
  <input value="" name="n1" id="n1" type="text"/>
  <input value="Send" type="button"/> 
</form>
<script>
  $('#submitme').bind( 'submit', function() {
       if ($.data( $('#submitme' ), 'validated'))
           return true;
       $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) {
             if (data == "true") {
                $.data( $('#submitme'), 'validated', true );
                $('#submitme').submit();
             }
       }); 
       return false;
  });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜