tomaytotomato
tomaytotomato

Reputation: 4028

Passing an array value into the jQuery selector method?

At the moment in my JS I statically define which input ID's I want to associate my datepicker script with.

Like so:

$('datepicker1').glDatePicker();

However to make this dynamic I have refactored this into a for loop so that for multiple fields that need a datepicker I can call them in that loop.

dateArray[y] =  "datePicker" + i;
//out of loop scope

for (i = 0; i < dateArray.length; i++)
    {
        $(dateArray[i]).glDatePicker();

    }

It does not seem to work , I have checked that there are values in the array by printing the values to the log.

Is this a limitation of jQuery?

Thanks

Upvotes: 1

Views: 117

Answers (3)

Jose Rui Santos
Jose Rui Santos

Reputation: 15319

It is better to make a single jQuery call to glDatePicker(), by concatenating all ids into a string

var allIds = '';
for (i = 0; i < dateArray.length; i++) {
  allIds += '#' + dateArray[i] + ',';
}
$(allIds).glDatePicker();

Or even better, put a class to all those fields, and simply call

$(".datepicker").glDatePicker();

There is still another single call solution (assuming all your ids start with "datePicker"):

$('[id^="datePicker"]').glDatePicker(); // selects all elements that have id starting with datePicker

Upvotes: 1

bipen
bipen

Reputation: 36531

which input ID's I want to associate my datepicker script with.

i think you missed the id selector

$('#'+ dateArray[i]).glDatePicker();
---^---here

Upvotes: 1

Anton
Anton

Reputation: 32581

You need to set it as an id with "#"

 $("#" + dateArray[i]).glDatePicker();

Upvotes: 3

Related Questions