lincstar182
lincstar182

Reputation: 59

$('form:not(.some-class)').keydown is still applying keydown event to .some-class

JQuery's ':not' selector is not preventing the intended-to-be-excluded class (which decorates an element) from firing the .keydown event. Why?

From the following code, when I press a key in the .newOwnerEntryInput field, I expect to see the alert for '1' only. But I see both alerts '1' and '2'.

Javascript:

$('.newOwnerEntryInput').keydown(function (event) {
    alert('1');
});

// Prevent Enter from submitting form.
$('form:not(.newOwnerEntryInput)').keydown(function (event) {
            alert('2');
});

HTML:

<li style="position: relative">
    @Html.DropDownList("cftMemberID", null, String.Empty, new { @class = "actionOwnerDropDown hidden" })
    <div class="newOwnerEntryDiv">
        <input class="newOwnerEntryInput" />
        <div class="float-right closeNewOwner">
            <img src="~/Images/cancel_x.png" alt="close" />
        </div>
    </div>
</li>

I have tried a variety of quotes styles, with and without surrounding the excluded class with quotes, as well as adding 'input' after the class, as in $('form:not(.newOwnerEntryInput input)').keydown

Thanks!

Upvotes: 0

Views: 439

Answers (3)

Jason Cidras
Jason Cidras

Reputation: 507

Try this:

HTML:

<div>
   <input class="newOwnerEntryInput" type="text"/><br />
   <!-- I know you have MVC dropdown list, but I replaced it with a html textbox (for simple testing) -->
   <input class="newOwnerEntryInput1" type="text"/>
</div>

JavaScript:

$('input.newOwnerEntryInput').keydown(function (e) {
    alert('1');
});

$('input:not(.newOwnerEntryInput)').keydown(function (e) {
    alert('2');
});

I checked with the documentation that in their example, I saw they had the element input followed by the function with the selector.
The documentation is available is here: jQuery :not()

I hope this helps!
Cheers!

Upvotes: 1

lincstar182
lincstar182

Reputation: 59

Thanks for those who helped. I do need the form to fire for ALL types of input fields, not just those of type input. So that was out.

Here is what solved my problem:

$('form').keydown(function (event) {
    if (! event.which.hasClass('.newOwnerEntryInput')) {
        alert('2');
    }
});        

In this case, for my input of class .newOwnerEntryInput, if a key is pressed, it will NOT fire the event and push '2' out to the alert screen.

Again, thanks, it took a couple responses, all of which had a piece of the solution, for me to answer this myself. :)

Upvotes: 2

DinoMyte
DinoMyte

Reputation: 8858

Try this :

$('form input:not(.newOwnerEntryInput)').on('keydown',function (event) 
{
      alert('2');
});

http://jsfiddle.net/rzseLj27/

Upvotes: -1

Related Questions