How to get value from text input on blur of field
Sehummel’s Question:
I’m trying to write some Javascript to get the value from two text inputs, which should be fairly straightforward. But something is amiss. Here is my code:
<script>
jQuery(function() {
jQuery('#fromPicker, #toPicker').datepicker({ dateFormat : 'yy-mm-dd' });
jQuery('#submit').attr('disabled', 'disabled');
jQuery('#toPicker').on('blur', function() {
var fromDate = jQuery('#fromPicker').val();
var toDate = jQuery('#toPicker').val();
console.log(toDate);
if (fromDate !== '' && toDate !== '') {
if (isValidDate(fromDate) && isValidDate(toDate)) {
jQuery('#submit').removeAttr('disabled');
} else {
alert('You must enter dates in the format "yyyy-mm-dd"');
}
}
});
});
function isValidDate(dt) {
if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) {
return true;
}
}
</script>
When I console.log(toDate)
however, I get an empty string. But if I do another blur
event again (focus and unfocus the field with the data still in it), I get the correct value. Any ideas why it doesn’t work the first time?
The two text inputs have IDs of #fromPicker
and #toPicker
and are jQueryUI datepickers.
SOLUTION:
What ultimately did what I wanted was this:
jQuery(function() {
jQuery(‘#fromPicker, #toPicker’).datepicker({
dateFormat : ‘yy-mm-dd’
});jQuery('#submit').on('click', function() { var fromDate = jQuery('#fromPicker').val(); var toDate = jQuery('#toPicker').val(); if (fromDate !== '' && toDate !== '') { if (isValidDate(fromDate) && isValidDate(toDate)) { // do nothing } else { alert('You must enter dates in the format "yyyy-mm-dd"'); return false; } } else { return false; } }); }); function isValidDate(dt) { if (dt.match(/^[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/)) { return true; } } </script>
I dont see any reason for your code not to work but instead of blur
event, try onselect
event of the datepicker instead
jQuery('#toPicker').datepicker( {
onSelect: function(date) {
alert(date);
// Do other stuff
},
// ....
);