JGV
JGV

Reputation: 5187

Retain previously selected value in jquery-ui datepicker

I have a datepicker which is displayed on a custom button click event. The user selected date is then populated in a textbox. By default, the datepicker selects a past date (-3 days).

Issue:

The issue I am facing is, the previously selected date is not retained on the textbox upon subsequent custom button clicks.

Fiddler:

https://jsfiddle.net/99x50s2s/142/

HTML

<br/>
<div class="form-horizontal">
  <div class="form-group">
    <label class="control-label col-xs-3">From Date </label>
       <div class="col-xs-6">
          <div class="input-group">
             <input class="form-control" id="AddDateFromTxt" type="text" maxlength="10">
               <span class="input-group-btn">
                  <button type="button" class="btn btn-default" id="AddDateFromBtn" title="Click here to select 'Add Date From'"><i class="glyphicon glyphicon-calendar"></i></button>
               </span>  
           </div>
         </div>
       </div>
     </div>  

JS

var fromDateCtrl = $('#AddDateFromTxt');

$('#AddDateFromBtn').on('click', function () {
    fromDateCtrl.datepicker().datepicker("setDate", "-3").datepicker("show");        
});

Expectation

If I select 11/1/2015 on first time then, on the next click of calendar button, the values in textbox should not change to 11/4/2015 and should remain the same as 11/1/2015.

Upvotes: 0

Views: 2860

Answers (1)

Andreas
Andreas

Reputation: 21881

Only set the date if there isn't one selected/set yet.

$('#AddDateFromBtn').on('click', function () {
    var dp = fromDateCtrl.datepicker();

    if (dp.datepicker("getDate") == null) {
        dp.datepicker("setDate", "-3");
    }

    dp.datepicker("show");
});

https://jsfiddle.net/wbuo2z9w/

Upvotes: 3

Related Questions