1

I have two forms without id, I could have more, when I try to validate with JQuery Validation Plugin It is successful but the message is placed always inside first form.

<form class="myform" action="http://www.google.com">
    <input type="text" name="mytext"/>
    <button class="mybutton">Send</button>
</form>
<form class="myform" action="http://www.google.com">
    <input type="text" name="mytext"/>
    <button class="mybutton">Send</button>
</form>

The JQuery Validation is

    <script>
        $(function () {
            $('.myform').validate({
                rules: {
                    mytext: 'required'
                },
                messages: {
                    mytext: 'Required field'
                }
            });
            $('.mybutton').click(function () {
                var form = $(this).closest('.myform');
                console.log("Action form is: " + form.attr('action'));
                form.valid();
            });
        });
    </script>

When I press the button, I know the validation is successful because the output is Action form is: http://stackoverflow.com when I press the first button, and Action form is: http://www.google.com when I press the second button.

Is there any way to place the error in the correct form?

Example in JSFiddle

2
  • Are you not able to add something unique to the form ? Commented Sep 16, 2015 at 13:41
  • Yes, I could but I must try to do only with class selector because my client doesn't want many changes. I think the problem is in the JQueryValidation plugin when It searches for the input in the form. Commented Sep 16, 2015 at 13:46

1 Answer 1

1

You can use .each() loop:

$('.myform').each(function(){
    $(this).validate({
        rules: {
            mytext: 'required'
        },
        messages: {
            mytext: 'Required field'
        }
    });
});

JSFiddle

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.