0

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.

3 Answers 3

1

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.
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

You should call validate() outside of the click handler. Otherwise you're setting the form up for validation every time you click, which you don't need to do.
@AndrewWhitaker: Thanks, I updated my answer (and the fiddle)
0

Try adding event.preventDefault();

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

1 Comment

Nothing seems to have changed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.