0

On my page, there are two forms. I'd like to select only the one for which the submit button is clicked.

I would think the following should do the trick:

$("#signup,#login").submit(function(){
    $(this).parent("form:first").css('background-color', 'red');
    return false;   
});

But with the "form:first" selector, nothing happens (likely because it is selecting the container div). Without the "form:first" selector, the container div is selected.

http://jsfiddle.net/tenfold/gupGD/

Can anyone help with what's going on here? Many thanks.

1
  • $(this).parent().find('form:first') ?? Commented Feb 5, 2013 at 17:18

3 Answers 3

2

You could just do

$(this).css('background-color', 'red');

The submission event is bound to the form itself.

Also, you shouldn't use return false, but use the event as a parameter and call event.preventDefault()

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

5 Comments

"but use the event as a parameter and call event.preventDefault()" - generally that's true, but in this case stopping the event bubbling won't harm anything; submit events are only meaningful for forms.
@SamDufel indeed, but I'd rather teach the correct way to do this
+1 exactly @ExplosionPills, You always give great and precise answers. Was just trying to make the same point HERE
@ROYFinley you'll find it very hard to win an argument against any developer who knows what he's doing even if he's wrong.
@ExplosionPills Probably, right LOL... as my profile on here says, been doing it 18 years and learn something new every day.
2

You can use .closest() method

$("#signup,#login").submit(function(){
    $(this).closest("form").css('background-color', 'red');
    return false;   
});

2 Comments

I never knew that closest could select the element itself. That's an extra step, though.
@Explosion Pills You're absolutely right, in this particular example it's an extra step. The ability to test the element itself by .closest method is more useful when using mouse event types. I think your answer is more correct than mine.
0

You have to use parents() instead of parent().

Extract from doc here :

The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

1 Comment

Very nice comment but put it in comment section plz.

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.