user1049961
user1049961

Reputation: 2736

Jquery - the same click function for multiple elements with different id

I have cca 150 elements with the same name, except of the id. I need to bind the same click function to them. In the current code, the following gets generated 150 times, but I think there has to be more efficient way.

What would be the most efficient way to rewrite the following code?

<script>
    var jizda_1 = $('a#jizda_1');
    jizda_1.click(function(e) {
        e.preventDefault();
        id = 1;
        $('#jizda_' + cisloJizdy + '.active').removeClass('active');
        cisloJizdy = 1;
        if ($(this).hasClass('closed')) { // uzavrena jizda
            generujPoziceUzavreneJizdy(cisloJizdy);

        } else {
            generujPoziceOtevreneJizdy(cisloJizdy);
        }
        $(this).addClass('active');
        $('#detailZakaznika').hide();
        $('#tiskDokladu').addClass('disabled');
        $('#tiskUctenky').addClass('disabled');
    });
    var jizda_2 = $('a#jizda_2');
    jizda_2.click(function(e) {........
    });
</script>

Upvotes: 1

Views: 1702

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

I would change the HTML so the elements in question share a common class. Then:

$("a.the-class").click(...);

Within the click handler, use this (which will be the element clicked), either directly (it's the DOM element) or by wrapping it in a jQuery wrapper ($(this)), to refer to the specific element.

Live Example | Source

But you can select them by the common part of their id using the attribute-starts-with selector:

$('a[id^=jizda_]').click(...);

Live Example | Source

Upvotes: 4

Tomanow
Tomanow

Reputation: 7377

$('[id^="jizda_"]').each(function (k, v) {
    $(this).click(function (e) {
        e.preventDefault();
        id = k+1;
        $('#jizda_' + cisloJizdy + '.active').removeClass('active');
        cisloJizdy = k+1;
        if ($(this).hasClass('closed')) { // uzavrena jizda
            generujPoziceUzavreneJizdy(cisloJizdy);
        } else {
            generujPoziceOtevreneJizdy(cisloJizdy);
        }
        $(this).addClass('active');
        $('#detailZakaznika').hide();
        $('#tiskDokladu').addClass('disabled');
        $('#tiskUctenky').addClass('disabled');
    });
});

Upvotes: 0

Related Questions