dgrubelic / material-design-lite

Material Design Lite Components in HTML/CSS/JS
http://getmdl.io
Apache License 2.0
3 stars 6 forks source link

datepicker input change event #26

Closed vmateixeira closed 8 years ago

vmateixeira commented 8 years ago

Hi @dgrubelic, first of all thanks for your impressive work on continuing with the MDL new components development :) It's been proven really handy!

I've been testing your datepicker with angular2 and may need an advice. What do you think would be the best way to capture a date change event? I was thinking on capturing a (change) event on the input field value but realized the chosen date is not being held there. Any help on this?

Thanks again!

dgrubelic commented 8 years ago

Hi @vmateixeira, thank you for your feedback. :smile:

I found the best way to capture change event is on the mdl-datepicker container itself. Also, you can attach ng-model directive to the container (i went with this logic since input is optional element in datepicker - for inline pickers, for example). That way you get selected date Date object so you can do with it what ever you want.

You can attach it to input, but then you have only formatted date string and you have to parse it if you need to work with it (validation, etc).

<div id="date" class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label mdl-datepicker mdl-js-datepicker mdl-datepicker--fixed" ng-model="ctrl.date">
    <input class="mdl-textfield__input mdl-datepicker__input" type="text" name="from" required autocomplete="off"></input>
    <label class="mdl-textfield__label" for="date">Select date</label>
</div>

<script>
var datePicker = document.querySelector('#date');
// Change event is triggered on picker container AND picker input (if exists)
datePicker.addEventListener('change', function (e) {
    var selectedDate = datePicker.MaterialDatePicker.getSelectedDate();
});
</script>
vmateixeira commented 8 years ago

@dgrubelic, thank your for your advice and explanation! :)

I can see your point now on the input... I wasn't initially thinking on using the Date object, as I don't need the time part of it, but it sure makes more sense to pass it for validation and formatting purposes.

Your example illustrates really well what I want to achieve.

Thanks again for the good work! :)

dgrubelic commented 8 years ago

No problem, any time. :) Well, since this is "date" picker, it made sense that end result of this component is actually Date object, and not some formatted date string value.

Anyway, I believe we reached valid conclusion and answer for this question. Closing... :)