2

I have the following form:

<form class="uk-form">
  <label for="startDate">Start Date:</label>
    <input type="text"  id="startDate" data-uk-datepicker="{format:'YYYY-MM-DD'}">
  <label for="endDate">End Date:</label>
    <input type="text"  id="endDate" data-uk-datepicker="{format:'YYYY-MM-DD'}">
</form>

What I need is to call a JS function once one of those datapicker gets changed using .on() in JQuery.

I get it to work using only one with this code:

$('#startDate').on('change', function() {

However what I need is that when one of them changes to run the function, sort of like this:

$('#startDate'||'#endDate' ).on('change', function() {

Any ideas?

jquijano
  • 128
  • 3
  • 12

4 Answers4

1

or you can have

$("form").on('change', "#startDate, #endDate", function(event){...})

So you dont need to worry about replacing the element

Z.Z.
  • 674
  • 6
  • 16
1

To attach change event on more than one element you can use multiple selector. Another possibility is to use a class selector

Inside the event handler, to get the element for which the event is triggered you can use the event.target.

$(function () {
  // Multiple selector:
  // $('#startDate, #endDate').datepicker();
  // or, class selector:
  $(':text.dpClass').datepicker();
  
  //$('#startDate, #endDate').on('change', function(e) {
  $(':text.dpClass').on('change', function(e) {
    $('#log').text('Changed element is:' + e.target.id);
  });
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>

<p id="log"></p>
<form class="uk-form">
    <label for="startDate">Start Date:</label>
    <input type="text"  id="startDate" class="dpClass" data-uk-datepicker="{format:'YYYY-MM-DD'}">
    <label for="endDate">End Date:</label>
    <input type="text"  id="endDate" class="dpClass" data-uk-datepicker="{format:'YYYY-MM-DD'}">
</form>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0

try: $('input').on('change', function () {

Of course if you have more inputs on the page it will fire for them too. So perhaps give both of the pickers unique class and add on handler to that class.

apieceofbart
  • 2,048
  • 4
  • 22
  • 30
0

Give both the inputs a name. and try this:

$("input[name='someName']").on('change', function() {});
vohrahul
  • 1,123
  • 10
  • 17