Dave
Dave

Reputation: 1775

$(this) returns wrong element when Jquery event binded to an entire class

I have several inputs that have the class specifierInput

I want this function to run when any of those are focus'd on (it does)

$('.specifierInput').focus(function (e) {
    if (isValidationErrorResponse($(this).val())) {
        $(this).val('');
        $(this).trigger('keyup');
    }
    $(this).css('color', 'black');
});

Some of my HTML

<textarea id="mfpIdentifierText" name="ASSerialNumber" class="specifierInput"style="width:99%; height:80px; resize:none;"><%= (Session["ASSerialNumber"] ?? "").ToString()%></textarea>

<input name="ASModel" class="specifierInput alphaNumericWithSpacesCommasDashes" type="text" value="<%= (Session["ASModel"] ?? "").ToString()%>"/>

My issue is that $(this) is returning the first element that has the specifierInput applied to it, rather than the element that the event fired for.

Upvotes: 0

Views: 687

Answers (2)

Daniel Larsen
Daniel Larsen

Reputation: 198

My version of jQuery is populating this with the element that fires the event, not necessarily the first element that meets fulfills the selector. Not sure why it's returning the first element for you.

In any case, you may want to see if the property e.target has the element you're looking for. From the jQuery API, e.currentTarget is not always the initiating element, but can be modified due to event bubbling. e.target will always be the initiating event.

jQuery event.target API

Upvotes: 1

gretro
gretro

Reputation: 2009

Look towards the jQuery Proxy here : http://api.jquery.com/jquery.proxy/

A proxy will set the right 'this'.

Upvotes: 0

Related Questions