简体   繁体   中英

Can't use JQuery form validation with two buttons html form

HTML:

<form id="myForm">
    <fieldset>
        <ol>
            <li>
                <label for="data">Data</label>
                <input id="data" name="data" type="text" placeholder="Ex.º: 14-02-2014" required>
            </li>
            <li>
                <label for="conta">Conta</label>
                <input id="conta" type="text" name="conta" placeholder="Ex.º: " required>
            </li>
        </ol>
        <input id="oknovo" type="submit" value="OK & Novo" />
        <input id="okfechar" type="submit" value="OK & Fechar" />
    </fieldset>
</form>

JS:

$(document).ready(function () {

    var form = $('#myForm');
    var botao;

    form.validate();
    if (form.valid()) {
        $("#myForm input[type=submit]").click(function (event) {
            botao = $(this).attr('id');
            alert("clique " + botao);
        });
    };
});

I want to validate the form using JQuery validation plugin.

If it is valid according to the rules specified in the HTML form, then identify which of the buttons was clicked. The validation plugin is working but the form is never valid, therefore the function is never called to alert the id of the button.

You may see a live JSFiddle here.

If the form isn't valid at DOM ready (which it will never be), then your code to add the event handler to the button won't run. You should consider running your validation on a different event, say when the text in the textbox changes.

Example:

$('input[type=textbox]').change(function() {
    // put your validation code here.
});

Put your validation inside the click event, and it starts working:

$(document).ready(function () {

    var form = $('#myForm');
    var botao;
    form.validate();
    $("#myForm input[type=submit]").click(function (event) {
        if (form.valid()) {
            botao = $(this).attr('id');
            alert("clique " + botao);
        }
        event.preventDefault();
    });
});

Working fiddle

Try adding event.preventDefault();

    $("#myForm input[type=submit]").click(function (event) {
        event.preventDefault();
        botao = $(this).attr('id');
        alert("clique " + botao);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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