Leroy Mikenzi
Leroy Mikenzi

Reputation: 810

check if the value in a datepicker html element is empty and execute jquery function

I'm using a jquery datepicker in my form. I'm checking if the date is empty using jquery and checking if the date selected is a Sunday.

I'm using the Blur function as I couldn't find any event of a date picker that will check if the value is empty.

Using the Blur function I'm able to check if the date is sunday by executing Ajax in setinterval function.

But now the issue is that if I select the datepicker and if I exceed the time set in setinterval function. It doesn't perform the check whether the day is sunday. How can I solve this ? I know increasing the time interval can solve this but I wanted something like an event or somthing that can trigger the function to check if that date is sunday.

Following is my code.

datepicker element in html file below

<p class="datepair" data-language="javascript">
 <label>Day<em>*</em></label>
 <input type="text" id="date_o" placeholder="Please select date" class="date start" />
</p> 

Jquery function below:

$(function(){
    $('.datepair input.date').blur(function () {
        setTimeout(function () { 
          if($("#date_o").val() != '' ){
            var date_val = $("#date_o").val();
            $.ajax({
              data: 'date='+date_val,
              url:'common/ajax/date_check.php',
              success:function(data){
                if(data=="sunday"){
                  alert('Sorry You cant book on a Sunday.!!!');
                  $("#date_o").val('');
                }else{

                }
              }
            });
          }else{

          }
        },3000);
    });
  });

and the php file to check if the date is sunday. which works within 3 seconds that date_check.php:

if(date('w', strtotime($_REQUEST['date'])) == 0) {
  echo 'sunday'; 
}

Upvotes: 1

Views: 6416

Answers (1)

Ohgodwhy
Ohgodwhy

Reputation: 50787

Use the .onSelect() event:

$("#date_o").datepicker({
    onSelect: function(dateText, inst) {
        if($("#date_o").val() != '' ){
            var date_val = $("#date_o").val();
            $.ajax({
                data: 'date='+date_val,
                url:'common/ajax/date_check.php',
                success:function(data){
                    if(data=="sunday"){
                      alert('Sorry You cant book on a Sunday.!!!');
                      $("#date_o").val('');
                    }else{

                    }
                }
            });
        }
    }
});

You also don't need to use server side to check if the day is sunday:

$("#date_o").datepicker({
    onSelect: function(dateText, inst) {
        var d = new Date(dateText);
        if(d.getDay() == 0){
            alert('You cannot choose sunday!');
            $('#date_o').val('');
        }
    }
});

Here's a working jsFiddle

Upvotes: 3

Related Questions