jquery multiple ids same function jquery multiple ids same function jquery jquery

jquery multiple ids same function


You could use the "attribute starts-with" selector:

$(function() {    $("input[id^='datepicker']").datepicker({        showButtonPanel: true    });});

That selector will match any input element whose id value starts with "datepicker". An alternative would be to give all the required elements a common class.

You can also select multiple elements by id using a comma-separated list:

$("#datepicker0, #datepicker1, #datepicker2"); //List as many as necessary

But that's not particularly scalable if you ever need to add more inputs.


The best way is to use a class:

<td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker0"></td><td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker1"></td><td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker2"></td><td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker3"></td><td style="background-color:#c6efce"><input type="text" class="dp" id="datepicker4"></td><script>    $(function() {        $( ".dp" ).each(function(){            $(this).datepicker({                showButtonPanel: true            });        })    });</script>

but you can also use this:

<td style="background-color:#c6efce"><input type="text" id="datepicker0"></td><td style="background-color:#c6efce"><input type="text" id="datepicker1"></td><td style="background-color:#c6efce"><input type="text" id="datepicker2"></td><td style="background-color:#c6efce"><input type="text" id="datepicker3"></td><td style="background-color:#c6efce"><input type="text" id="datepicker4"></td><script>    $(function() {        $( "#datepicker0,#datepicker1,#datepicker2,#datepicker3,#datepicker4" ).datepicker({            showButtonPanel: true        });    });</script>

The second approach is not advised.


As I understand your question, you're trying to select multiple IDs using jQuery. Here's how you do that:

$('#1,#2,#3')

You just separate the IDs by commas.

But, this isn't the best way to accomplish this. You should really use a class: Assign each td a class and use:

$('td.myClass')

Alternatively, you could assign an ID to the table and select all of its td children. HTML:

<table id="myTable">    <td>text</td>    <td>text</td></table>

jQuery:

$('table#myTable td')