0

I have a HTML form containing 10 input elements and I want to call a function on keypress on each of those input elements except 2 of those

$(":input").live("keypress", function(e){ 
// something...
});

The above selector will work for all input elements. But I want to exclude 2 of my input elements (By id or By class) from the above code. How shall I do it? Is there an exclude/ not feature in css selector?

The other way of doing it can be by appending the id's of the input elements to be included by something like "keypress_" and then using

$("[id^=keypress_]").live("keypress", function(e){ 
// something...
});

But I donot want to change the HTML ids. Can this be done by css selector?

2
  • Are you sure you want a pure CSS selector and not use any of the ones jQuery offers? Because :input is not a CSS selector. Commented Feb 8, 2013 at 6:23
  • Sorry.. I thought :input is a CSS selector. Anyways :input:not([id^=keypress_]) has done the trick for me Commented Feb 8, 2013 at 7:04

2 Answers 2

3

You can either use :not selector or the .not jQuery method. Both should work the same in this case.

$(":input:not([id^=keypress_]")
$(":input").not("[id^=keypress_]")

Do not use .live as it has been removed in jQuery 1.9. Use event delegation via .on instead:

$(document).on('keypress', ':input:not([id^=keypress_])', function () {
Sign up to request clarification or add additional context in comments.

Comments

0

There's a :not() selector in jQuery, and also a .not() method.

This may work for you:

$(":input:not([id^=keypress_])")

Or this:

$(":input").not("[id^=keypress_]")

This link may have more information. http://api.jquery.com/not-selector/

Comments

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.