0

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?

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

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

3 Comments

You don't need to go through all this. Use .valid() inside your click handler to force a test of the form.
nice solution.. saved my time.. every time we don't need to validate whole form.
Exactly. It's less characters, no extra lines needed, and is quicker to run. I'm not sure what @Sparky means when he says "go through all this".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.