-3

I have some code where I have a simple Bootstrap datepicker <input type="date"/> I need to check whether a value has been selected using JavaScript. When I echo the current value of the input where the date hasn't been selected, I just get a blank and the condition under if statement always results to true. Can someone assist in how to check this correctly?

\EDIT/UPDATE I can successfully get the value of the datepicker when a date has been selected. I use var date=$('#date').val() which works well when a date has been selected. But when a date hasn't been selected, it just returns a blank. I need to check for a situation where a date hasn't been selected and do something ... I have tried if(date="") and if(date=null) none of these are efficient. The function never jumps to the else. The if statement always results to true. Is there something I am doing wrong or is my approach totally out of question?

Wairimu Murigi
  • 2,157
  • 2
  • 15
  • 19
  • 4
    Check this link:- http://stackoverflow.com/questions/16681875/how-to-get-the-value-of-the-date-using-bootstrap-datepicker – Ravi Hirani May 23 '16 at 08:33
  • @RaviHirani I can successfully get the value of the datepicker when a date has been selected. I use `var date=$('#date').val()` which works well when a date has been selected. But when a date hasn't been selected, it just returns a blank. I need to check for a situation where a date hasn't been selected and do something ... I have tried `if(date="")` and `if(date=null)` none of this are efficient. Based on that can you assist me? – Wairimu Murigi May 23 '16 at 08:36
  • You should use == instead of = . single = is an assignment operator while == checks the condition. You can also write if(date) to check date is selected or not. – Ravi Hirani May 23 '16 at 10:02

1 Answers1

1

As mentioned in comment, you should write

var selectedDate = $("#date").val();
if(selectedDate == "") {  // use == instead of = here. It will check condition
  alert("date is not selected");
}else{
  alert(selectedDate);
}

Note:- single = is an assignment operator. It assigns the value to variable. While == checks the condition. You can also write if(selectedDate) to check date is selected or not.

Ravi Hirani
  • 6,511
  • 1
  • 27
  • 42