grayfield
grayfield

Reputation: 129

How to set a TextBox value when another TextBox value is changed

I have two textboxes with datepicker like this.

<script type="text/javascript">
    $(function () {
        $('#value_date').datetimepicker({ format: 'MM/DD/YYYY' });
        $('#run_date').datetimepicker({ format: 'MM/DD/YYYY hh:mm a' });
    });

</script>

<div class='input-group date' id='value_date'>
    <input type="text" id="txtValueDate" class="form-control" runat="server" placeholder="Value Date"/>
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
 </div>

<div class='input-group date' id='run_date'>
    <input type="text" id="txtRunDate" class="form-control" runat="server" placeholder="Run Date" />
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
 </div>

Then, when value_date's value changed, (e.g. 03/31/2016), the run_date is automatically set to value_date's yesterday (03/30/2016) as the default run_date, but still can be changed by datetimepicker. How I do this?

Upvotes: 0

Views: 531

Answers (3)

rev_dihazum
rev_dihazum

Reputation: 818

To get previous date, one approach could be as bellow(verbose code, because I have used functions of javascript Date):

$("#txtValueDate").change(function() {
   var valueDate = new Date($(this).val());
   var runDate = new Date();
   runDate.setDate(valueDate.getDate() - 1);//previous date
   $("#run_date").val(
                  (runDate .getMonth() + 1) 
                  + '/' + runDate.getDate()
                  + '/' + runDate.getFullYear()  
                  );
});

Upvotes: 1

DonerKebab
DonerKebab

Reputation: 520

i think you can use onselect event when value_date's value changed, something like:

$(".txtValueDate").datetimepicker({
onSelect: function(dateText) {
  var date = new Date();
  date.setDate(date.getDate()-1);
  var yesterday =  date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
  $('#txtRunDate').val(yesterday);
}});

Upvotes: 1

Iakovos Exadaktylos
Iakovos Exadaktylos

Reputation: 141

You should use the change event of the input box. Also you need to correct the id selectors you use. Finally, I sugest you include the momentjs library (link) to calculate and format the display of the previous day:

$('#txtValueDate').change(function(){   
  $('#txtRunDate').val(moment($(this).val()).subtract(1, 'days').format('MM/DD/YYYY'));
    });

Upvotes: 1

Related Questions