Set date to be initially empty in bootstrap-datepicker

Nyxynyx picture Nyxynyx · Jun 19, 2012 · Viewed 60.7k times · Source

I am using the bootstrap-datepicker in my site. The datepicker will be used to define search filters. I need the initial value of the datepicker input element to be empty, so it will not introduce the date filter for the search results. When the user clicks on the text input linked to Datepicker, the Datepicker popup box should select the first day of next month.

Problem: If I were to set an initial date (as shown below), the text input will be populated with today's date which is not what I want. However if i do not set the initial date, the datepicker will show 1970s. What should I do?

Similar to: The demo for jQueryUI Datepicker

JS Code

var now = new Date();
var nextMonth = new Date();
nextMonth.setDate(1);
nextMonth.setMonth(now.getMonth() + 1);
var prettyDate =  nextMonth.getMonth() + '/' + nextMonth.getDate() + '/' + nextMonth.getFullYear();
$('#listing_filter_available').val(prettyDate);
$('#listing_filter_available').datepicker();

HTML Code

<input type="text" id="listing_filter_available" class="input-small" placeholder="Date Available" />

Failed Attempt

Datepicker does not popup on clicking the text input el

$(function() {

    var now = new Date();
    var nextMonth = new Date();
    nextMonth.setDate(1);
    nextMonth.setMonth(now.getMonth() + 1);
    var prettyDate =  nextMonth.getMonth() + '/' + nextMonth.getDate() + '/' + nextMonth.getFullYear();
    $('#listing_filter_available').val('');  // clear the date filter
    $('#listing_filter_available').click( function() {
        $('#listing_filter_available').val(prettyDate);
        $('#listing_filter_available').datepicker();
    });

});

Answer

jshaw.ws picture jshaw.ws · Nov 6, 2013

There is a much easier way to do this! To set a value

$('#listing_filter_available').datepicker();
$('#listing_filter_available').datepicker('setValue', nextMonth);

To set a blank value

$('#listing_filter_available').datepicker();
$('#listing_filter_available').val('');