rybo111
rybo111

Reputation: 12588

jQuery Validate doesn't remove error if value is auto-inputted via JavaScript

My HTML looks like this:

<form id="mainform" method="post">
    <input type="text" class="required" name="receiver" />
    <span id="clickMe">Click me</span>
    <input type="submit">
</form>

And my JavaScript is as follows:

$(document).ready(function () {
    $("#clickMe").click(function() {
        $("input[name=receiver]").val("Clicked");
    });
    $("#mainform").validate({
        submitHandler: function (form) {
            alert("Success!");
            return false;
        }
    });
});

Fiddle: http://jsfiddle.net/Y9RFt/2/

If you submit leaving the input empty, an error appears.

If you click the 'Click Me' span, the input is auto-filled, but the error remains until you submit the form. If you type something instead, the error disappears instantly.

Is there a way to emulate user input so that the error disappears on click?

Upvotes: 0

Views: 1169

Answers (2)

Sparky
Sparky

Reputation: 98738

Simply use the built-in .valid() method to force an immediate validation test of the form.

$("#clickMe").click(function () {
    $("input[name=receiver]").val("Clicked");
    $("#mainform").valid();  // <<-- Add this line to force a test
});

DEMO: http://jsfiddle.net/Y9RFt/8/

Upvotes: 3

rybo111
rybo111

Reputation: 12588

Got it. The solution is to simply blur the input:

$("input[name=receiver]").val("Clicked").blur();

Fiddle: http://jsfiddle.net/Y9RFt/7/

Upvotes: 1

Related Questions