Joshua Joshua - 8 days ago 4
Javascript Question

Targeting Multiple tabs with a single key up function call

I am trying to build a DRY JQuery call that allows me to target several tabs within a form structure.

JQuery:

$(".subTabAction").keyup(function (event) {
if (event.keyCode == 13) {
$("#uniqueIdHere").click();
}
});


HTML:

`<span>
<span class="sr-only" id="anchor" tabindex="0">Main Content</span>
<span id="UniqueId1" tabindex="0" class="subTabAction">Details</span>
<span id="UniqueId2" tabindex="0" class="subTabAction">Duration</span>
<span id="UniqueId3" tabindex="0" class="subTabAction"></span>
@if (Model.blah.Count > 1)
{
<span id="blah" tabindex="0" class="subTabAction"></span>
}
@*<span class="sr-only" id="anchor" tabindex="0">Main Content</span>*@
</span>`


Each of the tabs has a unique id, and triggers an ajax call, the problem is I can only target one this way. I would like to be able to target each one separately so that they can be accessed with keyboard only.

Answer

$(".subTabAction") is a collection of multiple tabs because there are more elements with this class name. $(this) will give you the tab you targeted.

$(".subTabAction").keyup(function (event) {
    if (event.keyCode == 13) {
        $(this).click();
    }
});