Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI datepicker - clearing the altField when the primary field is cleared

I have a form with a datepicker. The datepicker has a user-facing d/m/Y formatted datepicker input and a hidden altField to go with it for use with the DB.

If the user clears the text in the input field it doesn't clear the altField as well.

I'm using the below JS to get around this problem. Is there a more correct way to do this or is it perfectly acceptable?

$("#datePicker").change(function(){
    if ($(this).val().length < 1){
        $("#dateAltField").val('');
    }
});
like image 655
bcmcfc Avatar asked Oct 13 '10 10:10

bcmcfc


3 Answers

What you have works just fine and is a valid approach, alternatively a bit shorter:

$("#datePicker").change(function(){
  if (!$(this).val()) $("#dateAltField").val('');
});
like image 186
Nick Craver Avatar answered Nov 16 '22 11:11

Nick Craver


According to this bug ticket it's not a bug, it's a feature.

I use this as workaround:

var $input = $('#myInput');
$input.dateinput();

// This is the main part:
$input.on('change', function(){
    if (!$input.val()) $input.data('datepicker').settings['altField'].val('');
});
like image 28
Michal Lohniský Avatar answered Nov 16 '22 13:11

Michal Lohniský


Generalization of mr Lohnisky solution and little flaw fix:

$("body").on("change",".hasDatepicker",function(e) {
   if ( !$(this).val() ) {
      $( $(this).data("datepicker").settings["altField"] ).val("");
   }
});
like image 1
Ruth Avatar answered Nov 16 '22 12:11

Ruth