5

On the website I'm currently working I have a form to add a event. This event needs a date which the user selects using a jQuery datepicker. A date can only have one event. So I want to check the date the user insert in the datepicker. I tried doing this by getting the value after the user has selected the date. The problem is however, the datepickers doesn't update his value right away.

I made a JSFiddle to show the problem. When you pick a date the span updates and shows the value of the datepicker. But as you can see the first time it is blank, and the second time it shows the previous selected date. So the datepickers does not update is value right away. How can I fix this?

I looked trough other similar questions here on stackoverflow but their solutions didn't work for me.

JSFiddle: http://jsfiddle.net/kmsfpgdk/

HTML:

<input type="text" id="datepicker" name="date" />
<span id="data"></span>

JS:

$('#datepicker').datepicker();

$('#datepicker').blur(function () {
    var val = $(this).val();
    $('#data').text(val);
});

3 Answers 3

7

Its better to use built in method onSelect:fn to use:

$('#datepicker').datepicker({
   onSelect: function () {
       $('#data').text(this.value);
   }
});

Fiddle


As per documentation:

onSelect

Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. this refers to the associated input field.

Sign up to request clarification or add additional context in comments.

1 Comment

The problem with this version is that it doesn't work with manually typing in data. If the user tabs or clicks away without touching the datepicker, the update function does not trigger.
1

change event happens before blur event.

Use .change() instead of .blur()

$('#datepicker').change(function() {
    var val = $(this).val();
    $('#data').text(val);
});

Updated jsFiddle Demo

Comments

-1

If Google brought you here because your input does not seem to respond to various JQuery .on( events, most likely it's because you have another element on the same page with the same id.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.