Проверьте элемент формы без / перед отправкой формы с помощью JavaScript - PullRequest
0 голосов
/ 28 июня 2019

У меня есть HTML-форма, элементы которой отображаются в различных модальностях Bootstrap. Первый модал имеет текстовое поле ввода и кнопку «Далее», чтобы открыть следующий модал. Когда нажата кнопка «Далее». Я хочу проверить, является ли текстовое поле пустым, и вызвать сообщение проверки. Форма не отправляется до самого конца. Все, что я пробовал, до сих пор не сработало.

Javascript / jQuery код

$("#add_assistant_next").click(function () {
        var textInput = document.getElementById('add_assistant_user');
        var text = textInput.value;

        if (text === "") {
            textInput.setCustomValidity('Please fill out this field.');
            textInput.checkValidity();
            var form = $('#form_add_assistant');
            form.find(':submit').click();
        } else {
            textInput.setCustomValidity('');
        }
    });

HTML

<form name="add_assistant" method="post" id="form_add_assistant">
        <div class="modal-body">
            <div class="step">
                <span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
            </div>
            <div class="pl-3 pt-1">
                <div>
                    <input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />
                    <button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
                </div>
                <input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
            </div>
        </div>

... form continues in other modals

Ответы [ 2 ]

1 голос
/ 28 июня 2019

Ваш JS-код, вероятно, борется с Bootstrap за контроль над этой кнопкой.Чтобы обойти это и получить подтверждение, вы можете попытаться изменить свой код, чтобы иметь промежуточную кнопку / временную кнопку, чтобы помочь с проверкой в ​​первую очередь перед фактической отправкой.Так что-то вроде этого:

код Javascript / jQuery

$("#my_temp_button").click(function () {
    var textInput = document.getElementById('add_assistant_user');
    var text = textInput.value;

    // Might also want to handle null and undefined cases?
    if (text === "" || text === undefined || text === null) {
        // I'm assuming if it's empty, it doesn't pass validation,
        // so we just display this warning and wait for the user to fix it:
        textInput.setCustomValidity('Please fill out this field.');
    } else {
        // it's not empty so validate:
        if (textInput.checkValidity()) {
            // it passed validation, so ok to submit. 

            // call the real button:
            $('#add_assistant_next').click();

            // do you need this?
            var form = $('#form_add_assistant');
            form.find(':submit').click();
        } else {
            // it failed validation, so display another error?
            textInput.setCustomValidity('Try again.');
        }
    }
});

HTML:

<form name="add_assistant" method="post" id="form_add_assistant">
    <div class="modal-body">
        <div class="step">
            <span class="fas fa-arrow-right choose-arrow mr-1"></span>1. Choose a user to add
        </div>
        <div class="pl-3 pt-1">
            <div>
                <input type="text" id="add_assistant_user" name="add_assistant[user]" required="required" placeholder="UCInetID or UCI email address" class="mr-0 form-control" />

                <!-- Feel free to change the id name. This is the button the user sees. It's only purpose is to give your function above full control to it and prevent Bootstrap from touching it and jumping to the next modal without having the user fix the validation failure first: -->
                <button type="button" id="my_temp_button" class="btn btn-outline-secondary btn">Look up user</button>

                <!-- Hide the real button from the user: -->
                <div style="display:none">
                    <button type="button" id="add_assistant_next" name="add_assistant[next]" data-toggle="modal" data-target="#add-user-modal" class="btn btn-outline-secondary btn">Look up user</button>
                </div>
            </div>
            <input type="hidden" name="user_search_route" value="/courseSpace/20900/listAssistantEnrollment">
        </div>
    </div>
    ...
0 голосов
/ 28 июня 2019

Вы пытались добавить ловушку для самого события submit?

$('#form_add_assistant').submit(function(evt){
    //do your validation here
    if (validation fails){
        return false; // OR, alternatively, `evt.preventDefault()`
    }
    //form submission will continue if not returned false
});

Ссылки:

https://api.jquery.com/submit/

Как проводить руководствопроверка формы через jQuery .submit ()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...