Reputation: 103
I have a form with several date fields. These date fields are actual text fields as I want to control the date structure from the start.
<div class="form-group col-md-6 col-xs-13">
<?php echo form_error('eindDatum'); ?>
<label for="eindDatum"><?php echo $this->lang->line('eindDatum'); ?><small class="text-info"><?php echo ' ' . $this->lang->line('datumNotatie'); ?></small></label>
<input type="text" name="eindDatum" id="eindDatum" class="form-control date" placeholder="DD-MM-YYYY" required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-[0-9]{4}">
</div>
<div class="form-group col-md-6 col-xs-13">
<?php echo form_error('aanvangDatum'); ?>
<label for="aanvangDatum"><?php echo $this->lang->line('aanvangDatum'); ?><small class="text-info"><?php echo ' ' . $this->lang->line('datumNotatie'); ?></small></label>
<input type="text" name="aanvangDatum" id="aanvangDatum" class="form-control date" placeholder="DD-MM-YYYY" required pattern="(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-[0-9]{4}">
</div>
I was looking for a formatter online to automatically insert the - (dash) between the structures. But my knowledge of JavaScript is really limited. I tried with using the class selector but that does not seem to work at all.
var date = document.getElementsByClassName('date');
And then I added a class of date to the input text fields
I (am trying to) work with this https://codepen.io/tutsplus/pen/KMWqRr
Any help would be greatly appreciated. If possible tell me why you are approaching it in a specific way so I can learn from your experience.
Upvotes: 1
Views: 151
Reputation: 32145
In the link you shared they are applying
the function to a single element
as they are getting it by id
.
In your case you tried to get it by its class
in that case it won't work because the date
variable will contain a collection
of elements
, so you need to loop over this collection to add the event listener properly to each element
.
Your code should look like this:
var dates = document.getElementsByClassName('date');
Array.from(dates).forEach(function(element) {
element.addEventListener('input', inputFunction);
element.addEventListener('blur', blurFunction);
});
Note:
I made two functions for both events
, all you need to do is to put the code inside the eventlisteners in your link respectively inside these two functions:
function inputFunction(e) {
//The input event code will be here
...
}
function blurFunction(e) {
//The blur event code will be here
...
}
Upvotes: 3