0

I have two tables that need to have different IDs or they will not work. I'm using 3rd party data table code that uses the ID to differentiate between the different tables in the browser.

<table id="promo" class="display">
<table id="official" class="display">

But I need to them to both link to the same script function. As you can see below, I have one for #promo and one for #official but they are both using the exact same code:

$(document).ready(function() {
    $('#promo').DataTable( {
        // does a TON of stuff here
    } );

    $('#official').DataTable( {
        // does a TON of stuff here
    } );

Is there a way to make both tables link to the same code in a script?

1
  • I think it is good to know that there is good reason why the tables need different IDs to work — non-unique IDs are not semantically valid in HTML, and browser behavior is technically undefined when encountering non-unique IDs, although they tend to simply select the first occurrence. Commented Dec 2, 2014 at 1:57

3 Answers 3

6

Is there a way to make both tables link to the same code in a script?

Yes:

$('#promo, #official').DataTable( {
    // does a TON of stuff here
});

This uses a CSS group selector, but you can use any other selector that matches both elements. Based on your question, for instance, .display (a class selector) does as well (provided it doesn't also match other elements you haven't shown):

$('.display').DataTable( {
    // does a TON of stuff here
});
Sign up to request clarification or add additional context in comments.

Comments

4
$('.display').each(function(){
    $(this).DataTable({
        // does a TON of stuff here
    });
});

This way you will not have to add each and every id manually. Just add .display to the elements.

4 Comments

No you don't have to use each, jQuery will perform an implicit iteration here.
When is each() necessary?
Oops my bad, @dandavis is right. Well, I assume a good plugin will handle the stuff perfectly with jQuery style, including implicit iteration.
A plugin that requires each in this situation is a broken plugin that should be fixed or ditched.
0

Alternatively:

var $DTs = $(".someSemanticClassForAllIntendedTables"); //for easy reference elsewhere
$DTs.DataTable({ //options });

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.