1

I have this code:

$("form").submit(function() {
  $(":input").each(function() {
    if($(this).val() === "")
    alert("Empty Fields!!");
  });
});

It works great but when I have more than one form on a page, it checks all forms. I wan't to check only the submitted form using the "this" selector. How shall I implement the "this" selector in my code to check only the submitted form?

I cannot use any id's or classes, only the "this" selector.

1
  • as side notes, if you don't need to suport IE<10, you should use required attribute and $(this).val() is just more boring way to write this.value ;) As kind of polyfill for required attribute: stackoverflow.com/questions/17479573/… Commented Jan 26, 2015 at 13:28

1 Answer 1

4

Within the form submit handler you can use the this keyword to refer to the form which raised the event. Once you have that you could use find:

$("form").submit(function() {
    $(this).find(":input").each(function() {
        if ($(this).val() === "")
            alert("Empty Fields!!");
    });
});

Or a contextual selector:

$("form").submit(function() {
    $(":input", this).each(function() {
        if ($(this).val() === "")
            alert("Empty Fields!!");
    });
});

To retrieve the related input elements.

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

2 Comments

Rory, do you know how I can filter out all submit buttons in my code?
You could use :not(button), or manually place a class on the elements you want.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.