ni8mr ni8mr - 1 year ago 68
Javascript Question

Showing a hidden button based on the fill-up event of an input field

I have a datetime field and a hidden button. I want to show the button only when the datetime field is filled up. Here is my code -

HTML

<input type='text' id='datetimepicker'>

<button type="button" id="just-a-button" class="btn btn-primary pull-left">
Button
</button>


JAVASCRIPT

$('#datetimepicker').datetimepicker({
dateFormat: 'Y-m-d H:i'
});

$("#datetimepicker").focusout(function() {
if ($("#datetimepicker").val()) {
$('button#just-a-button').show();
}
});


Live demo is here.

Button becomes visible when outside area of the input field is clicked after datetime selection.

I want to make the button visible instantly after datetime selection. How can i achieve this ?

Answer Source

listen to change event and reuse jQuery objects like this:

$("#datetimepicker").change(function() {
  if ($(this).val()) {
    $('button#just-a-button').show();
  }
});

EDIT: alternative solution (and possibly better) - you can use callback function provided by the plugin as written here:

$('#datetimepicker').datetimepicker({
  dateFormat: 'Y-m-d H:i',
  onChangeDateTime: function() {
    $('button#just-a-button').show();
  }
});

..this way you can remove the code from first solution, also you can play around with this callback function to target multiple datetimepicker objects with single code

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download