program tip

e.preventDefault () 호출 후 양식 제출

radiobox 2021. 1. 6. 08:01
반응형

e.preventDefault () 호출 후 양식 제출


여기서 간단한 양식 유효성 검사를 수행하고 있으며 매우 기본적인 문제에 갇혀 있습니다. 이름과 앙트레 (저녁 등록을 위해)를위한 5 개의 필드 쌍이 있습니다. 사용자는 1-5 쌍을 입력 할 수 있지만 이름이있는 경우 앙트레를 선택해야합니다. 암호:

http://jsfiddle.net/eecTN/1/

<form>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    <input type="submit" value="Submit">
</form>
// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                return false;
            }
        }
    });

    $('form').unbind('submit').submit();

});

오류 메시지가 작동하지만 매번 양식을 제출합니다. 이 줄에 문제가 있음을 알고 있습니다.

$('form').unbind('submit').submit();

...하지만 내가 무엇을해야할지 잘 모르겠습니다.


가장 간단한 해결책은 단지입니다 하지 전화 e.preventDefault()유효성 검사가 실제로 실패하지 않는. 내부 if내부로 해당 줄을 이동 하고 .unbind().submit().


네이티브 element.submit()사용하여 jQuery 처리기에서 preventDefault를 우회하고 return 문이 각 루프에서만 반환되며 이벤트 처리기에서는 반환되지 않습니다.

$('form').submit(function(e){
    e.preventDefault();

    var valid = true;

    $('[name="atendeename[]"]', this).each(function(index, el){

        if ( $(el).val() ) {
            var entree = $(el).next('input');

            if ( ! entree.val()) {
                entree.focus();
                valid = false;
            }
        }
    });

    if (valid) this.submit();

});

문제는 오류를 보더라도 메서드 return false의 콜백에 영향을 미치므로 오류가 .each()있어도 라인에 도달한다는 것입니다.

$('form').unbind('submit').submit();

양식이 제출됩니다.

validated예를 들어, 변수를 만들고 true로 설정해야합니다. 그런 다음, 콜백, 대신 return false, 세트 validated = false.

드디어...

if (validated) $('form').unbind('submit').submit();

이렇게하면 오류가없는 경우에만 양식이 제출됩니다.


$('form').submit(function(e){

    var submitAllow = true;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val()) {

            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });

    return submitAllow;

});

실제로 이것은 올바른 방법 인 것 같습니다.

$('form').submit(function(e){

    //prevent default
    e.preventDefault();

    //do something here

    //continue submitting
    e.currentTarget.submit();

});

늦어서 미안하지만 완벽한 형태를 만들려고 노력 할게요 :)

I will added Count validation steps and check every time not .val(). Check .length, because I think is better pattern in your case. Of course remove unbind function.

My jsFiddle

Of course source code:

// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    var formIsValid = true;

    // Count validation steps
    var validationLoop = 0;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val().length > 0) {
            validationLoop++;

            // Find adjacent entree input
            var entree = $(el).next('input');

            var entreeValue = entree.val();

            // If entree is empty, don't submit form
            if (entreeValue.length === 0) {
                alert('Please select an entree');
                entree.focus();
                formIsValid = false;
                return false;
            }

        }

    });

    if (formIsValid && validationLoop > 0) {
        alert("Correct Form");
        return true;
    } else {
        return false;
    }

});

Why not bind the submit button event than the form itself? it would really much easier and safer if you bind the buttons than the form itself as the form will mostly submit unless you will use preventDefault()

$("#btn-submit").on("click", function (e) {
    var submitAllow = true;
    $('[name="atendeename[]"]', this).each(function(index, el){
        // If there is a value
        if ($(el).val()) {
            // Find adjacent entree input
            var entree = $(el).next('input');

            // If entree is empty, don't submit form
            if ( ! entree.val()) {
                alert('Please select an entree');
                entree.focus();
                submitAllow = false;
                return false;
            }
        }
    });
    if (submitAllow) {
        $("#form-attendee").submit();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form-attendee">
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    Name: <input name="atendeename[]">
    Entree: <input name="entree[]"><br>
    <button type="button" id="btn-submit">Submit<button>
</form>

ReferenceURL : https://stackoverflow.com/questions/22363838/submit-form-after-calling-e-preventdefault

반응형