Vue.js and jQuery datepicker / timepicker two-way binding

Bilateral binding with Vue.js using the <input> element does not work when jQuery datepicker and / or timepicker updates the value of <input> . Binding occurs only when the user types inside the <input> .

I need the two-way binding to be done when the <input> updated via datepicker or timepicker.

I use Vue.js and jQuery in the easiest way - importing them from my html file using the <script src=""></script> .

This question is known and has solutions , but for more complex situations than mine. Itโ€™s hard for me to understand how to adapt the solutions that I found to my main use case (i.e. I donโ€™t use custom directives, components or event templates).

Here is the code of my working code .

And here are the main parts of my static code:

 <form> <input v-model="title" name="title" type="text"> <input v-model="shortDesc" name="shortDesc" type="text"> <input v-model="date" name="date" type="text"> <input v-model="time" name="time" type="text"> </form> <script> var elm = new Vue({ el: '#preview', data: { title: '', shortDesc: '', date: '', time: '' } }) $(function(){ $("input[name=date]" ).datepicker({ dateFormat: 'DD, MM dd' }); }); $('input[name=time]').timepicker({'scrollDefault': 'now'}); </script> 
+10
jquery data-binding jquery-ui-datepicker
source share
2 answers

I can't find a vue vue way for this, but you can do it using the onSelect datapicker callback, you can set the value of the date variable in this callback.

See working code here .

I added the mounted block to my vue instance:

 var elm = new Vue({ ... ... mounted () { var vm = this $('#datedate').datepicker({ onSelect: function(dateText) { vm.date = dateText } }) }) 

and added in the id attribute in your date entry:

 <input v-model="date" name="date" class="block col-12 mb1 field" type="text" id="datedate"> 

EDIT

Since timepicker does not have the onSelect option that datepicker does, the solution should use the changeTime event , which is shown in the action in the "Event Example" in the demo docs timepicker>.

The code below shows the updated Vue script solutions for jQuery datepicker and timepicker:

 var elm = new Vue({ ... ... mounted() { var vm = this $('input[name=date]').datepicker({ dateFormat: 'DD, MM dd', onSelect: function(dateText) { vm.date = dateText } }), $('input[name=time]').timepicker({'scrollDefault': 'now'}).on('changeTime', function() { vm.time = $('input[name=time]').val(); }) } }) 

And here is the new codepen checking the @saurabh datepicker solution and @BrianZ timepicker solution .

+13
source share

This approach allows vue to pick up the changes, rather than manually setting the vm value to vm select, as in other answers.

 $('#datedate').datepicker({ onSelect: function(dateText) { $(this)[0].dispatchEvent(new Event('input', { 'bubbles': true })) } }); 
+2
source share

All Articles