on click input type date but var $(#date).value is empty

<input type="date" class="form-control" id="date" name="date" required>

whin I click on type=”date” alert is showing. How I get the date with I click on the date input.

<script>
$("#date").click(function () {
  var date = $('#date').val(); 
    if(date == ''){
       alert('Error; Date is empty');
        return;
    }
    $('#name').html('');
    $('#name').html('<option>Select Name</option>');
    $.ajax({
      type:'post',
      url: 'recording.php',
      data : { date : date},
      success : function(data){
         $('#name').html(data);
      }

    });
});
</script>

Answer

With your code, at the begining before you enter/choose date, you have to click on input field which will trigger alert that date is empty.

You should change your event to change instead of click, so when the change happens then check for date (change will happen on input lose focus or enter key inside of input):

Also after we get an event change, inside of it, we can use $(this) so we get the element that is currently changed in this case it is #date.

<script>
$("#date").on('change', function() {
  var date = $(this).val(); 
    if(date == ''){
       alert('Error; Date is empty');
        return;
    }
    $('#name').html('');
    $('#name').html('<option>Select Name</option>');
    $.ajax({
      type:'post',
      url: 'recording.php',
      data : { date : date},
      success : function(data){
         $('#name').html(data);
      }

    });
});
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *