JSFiddle - React, Tailwind, and code Playground
by IagoSRL
HTML
<script src="https://knockoutjs.com/downloads/knockout-3.5.0.js"></script>
<form>
<label>Text:
<input type="text" data-bind="textInput: text, enable: isEnabled"/>
</label>
<label>Date:
<input type="date" data-bind="textInput: textDate, enable: isEnabled"/>
</label>
<button type="button" data-bind="click: reset">JS reset</button>
<button type="button" data-bind="click: toggleEnabled">Disable/Enable</button>
<button type="button" data-bind="click: setDate">Set date 2020-01-02</button>
<!--<button type="reset">Native reset</button>-->
<p>Date 'as is': <output data-bind="text: aDate"></output></p>
<p>Date formatted: <output data-bind="text: formattedDate"></output></p>
<p>Text: <output data-bind="text: text"></output></p>
</form>
JavaScript
function AppViewModel() {
this.text = ko.observable('');
this.aDate = ko.observable(new Date());
this.isEnabled = ko.observable(true);
this.toggleEnabled = () => this.isEnabled(!this.isEnabled());
this.textDate = ko.pureComputed({
read() {
const d = this.aDate();
if (d) return new Date(d).toISOString().substr(0, 10);
else return '';
},
write(value) {
if (value) this.aDate(new Date(value));
else this.aDate(null);
},
}, this);
this.reset = function() {
this.aDate('');
this.text('');
};
this.formattedDate = ko.pureComputed(() => {
try {
const d = new Date(this.aDate());
return d.toISOString();
}
catch (_) {
return 'Invalid date';
}
});
this.setDate = () => this.aDate(new Date(2020, 0, 2));
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());