0

I'm using this js-datepicker plugin (https://www.npmjs.com/package/js-datepicker). The problem is I have a lot of fields I want to apply the same type of date picker so presumed I could just give them all a class of say 'year', however it only assigns it to the first input field with that class. Is there a way to apply to all inputs with that class?

my code:

const year = datepicker('.year', {
/*  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value // => '1/1/2099'
  }*/
});
karl
  • 321
  • 3
  • 16
  • 1
    Looks like this wants to initialize for one element at a time only, so you will need to select all your .year elements and loop over them, and then call the datepicker function for each one individually. – 04FS Mar 08 '19 at 11:29
  • They would all be assigned to same const variable, that's why it is appended only to the first element. You'd have to create an array of const and possibly differentiate the DOM elements by something more specific like an id value – Davide Vitali Mar 08 '19 at 11:29

2 Answers2

0

Maybe you can simply use input type "date" to have a quick working solution. Advantage: Format is chosen based on the current settings of the user, no need to format anything.

<input type="date" value="2019-01-01">
Aaron
  • 16
  • 3
  • Hi Aaron, yes this is how I first wanted to do it but unfortunately there's no way of customising the output, it has to go into a specific date format which is likely different to the browser preference. – karl Mar 08 '19 at 12:14
0

Looks like this wants to initialize for one element at a time only, so you will need to select all your .year elements and loop over them, and then call the datepicker function for each one individually.

Basically something simple like this should do,

var fields = document.querySelectorAll('.year');

fields.forEach(function(e) {
  datepicker(e, {})
});

If you need the references to the datepicker instances to be able to modify options later on or something like that, you could add them to an array inside the loop.

04FS
  • 5,660
  • 2
  • 10
  • 21