add class to input and label when datepicker is active?

I'm trying to create a form with styled input (sort of inspired by shopify's check out page) where the labels will show up when the user starts typing in the input. Everything seems working perfectly until I tried to add jQuery UI's datepicker widget.

Here's what my form looks like before typing in:

enter image description here

And this is what it looks like when I type in something:

enter image description here

As you can see, the label "birthday" is supposed to display after the user selected their birthday from the datepicker widget. But nothing shows up unless the user keys in the date themselves... any suggestion what I could do with the code?

Here's my jQuery:

// input
$('input[type="text"], input[type="password"]').on('keyup blur', function(){
    tmpval = $(this).val();
    if(tmpval == '') {
        $(this).removeClass('active')
        .siblings('label').removeClass('active');
    } else {
        $(this).addClass('active')
        .siblings('label').addClass('active');
    }
});
// date picker
$('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange: "-100:+0"
});

And here's part of my html:

<li>
    <label class="label" for="first_name">First name</label>
    <input type="text" id="first_name" placeholder="First name" />
</li>
<li>
    <label class="label" for="last_name">Last name</label>
    <input type="text" id="last_name" placeholder="Last name" />
</li>
<li>
    <label class="label" for="birthday">Birthday</label>
    <input type="text" id="birthday" class="datepicker" placeholder="Birthday" />
</li>

Any help would be appreciated! thanks!

(Also apologies if any of my words doesn't make sense since English isn't my first language.)

Answers 1

  • You need to set class on a select event of jquery datepicker. this need to help you.

    // input
     function setclass()
    {
      tmpval = $(this).val();
      if(tmpval == '')
      {
        $(this).removeClass('active')
        .siblings('label').removeClass('active');
      }
      else 
      {
        $(this).addClass('active')
        .siblings('label').addClass('active');
      }
    }
    $('input[type="text"], input[type="password"]').on('keyup blur', function()
    {
      setclass();
    });
    
    $('.datepicker').datepicker({
    changeMonth: true,
    changeYear: true,
    yearRange: "-100:+0",
    onSelect: function(dateText) 
      {
      setclass()
      }
    });
    

Related Articles