Ciarán
Ciarán

Reputation: 105

Using a Jquery plugin twice on a page

I have installed a JQuery date picker plugin. I have two dates that need to be picked.

  <div class="col-md-5">
    From:  <input id="datetimepicker" type="text" >
  </div>
  <div class="col-md-5">
    To:   <input id="datetimepicker2" type="text" >
  </div>

I have then called them in between script tags with

$('#datetimepicker').datetimepicker();
$('#datetimepicker2').datetimepicker();

This seems to work but I am wondering whether there is a neater way to do this regarding the way I have written the two lines above?

Upvotes: 0

Views: 99

Answers (4)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

You can also use like this:

$('[id^=datetimepicker]').datetimepicker();

But even better would be using a common class name for them and use like this:

$('.datetimepicker').datetimepicker();

Upvotes: 0

George
George

Reputation: 36784

Assuming .col-md-5 will always contain your datepicker inputs:

$('.col-md-5 input').datetimepicker();

Or even better; give your inputs a unique class, and use that:

HTML

<div class="col-md-5">
    From:  <input class="datetimepicker" id="datetimepicker" type="text" >
</div>
<div class="col-md-5">
    To:   <input class="datetimepicker" id="datetimepicker2" type="text" >
</div>

jQuery:

$('.datetimepicker').datetimepicker();

Upvotes: 2

Lix
Lix

Reputation: 47956

It depends on whether the plugin supports multiple selectors, but you can try supplying two selectors to the plugin:

$('#datetimepicker, #datetimepicker2').datetimepicker();

This same method is supported by jQuery as mentioned in the documentation.

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.


Another example would be to hide multiple elements at once:

$('#elem1, #elem2').hide();

In these instances one should consider using a class name to "group" elements together. One should use the id attribute when one and only one element is being dealt with.

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use comma separated multiple selector.Try this:

 $('#datetimepicker,#datetimepicker2').datetimepicker();

Upvotes: 2

Related Questions