afrocode afrocode - 3 years ago 184
jQuery Question

Date Picker after selecting an item on a dropdown

I'm trying to create an Input field that has drop down values. And if a certain item (Select Date) is selected, I would want it to show a datepicker to be able to select a date.

My issues are:


  1. The datepicker dialog doesn't pop-up right away if "Select Date" is selected. You have to click on the field again to show it.

  2. After the "Select Date" is selected, the datepicker is now being displayed every time the field is clicked. The datepicker should only show when the "Select Date" is chosen.



Here is my code:



$('.dropdown-menu a').click(function() {
var selectValue = $(this).attr('data-value');
var selectText = $(this).attr('data-text');

if (selectValue == 3) {
$('#date_select').datepicker({
daysOfWeekDisabled: "0,6",
autoclose: true,
todayHighlight: true
});
$("#date_select").datepicker("show");
} else {
$("#date_select").val(selectText);
}
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://uxsolutions.github.io/bootstrap-datepicker/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script>
<div id="pickDate" class="input-group dropdown date">
<input type="text" id="date_select" class="form-control" data-toggle="dropdown" required/>
<ul class="dropdown-menu" id="date_menu">
<li><a href="#" data-value="1" data-text="Soon">Soon</a></li>
<li><a href="#" data-value="2" data-text="Someday">Someday</a></li>
<li><a href="#" data-value="3" data-text="Select Date">Select Date</a></li>
</ul>
<span class="input-group-addon" data-toggle="dropdown">
<span role="button" class="caret"></span>
</span>
</div>





I'm using bootstrap datepicker.

Answer Source

Please take a look at modified code for issue #2

 $('.dropdown-menu a').click(function () {
  var selectValue = $(this).attr('data-value');
  var selectText = $(this).attr('data-text');
  if (selectValue == 3) {
  $('#pickDate').datepicker({
    daysOfWeekDisabled: "0,6",
    autoclose: true,
    todayHighlight: true
  });
    $('.ui-datepicker').css("display","block");
  }
  else {
    $('#date_select').val(selectText);

    $('.ui-datepicker').css("display","none");
  }
 });

This will show the datepicker only if you select option no 3 else it willbe hidden.

Let me know if it works for you.

For issue 1: Could you brief me about "You have to click on the field again to show it." What is your expected output?

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