如何根据下拉列表动态更改日期字段

时间:2018-09-04 11:53:58

标签: javascript jquery html

在这里,我想根据从下拉列表中选择的值自动显示日期。说,当我单击下拉列表的第一个值时,它必须在文本框中显示当前日期。同样,当我选择下拉菜单的第二个值时,它必须在15天后显示日期。

<div class="col-sm-3 form-group "><br>
  <label class="required">A Sample Dropdown when I select the value the date has to automatically get filled in the text box</label> <br>
  <select class="form-control" name="experience" required>
    <option value="">--values--</option>
    <option name="experience" value="0-1">Current date</option>
    <option name="experience" value="1-3">date after 15 days from current date</option>
    <option name="experience" value="3-5">date after 30 days from current date</option>
    <option name="experience" value="5-8">date after 45 days from current date</option>
    <option name="experience" value="8-11">date after 60 days from current date</option>
  </select>
</div><br><br>
<div>
  <input type="text" value="Display date here" />
</div>

1 个答案:

答案 0 :(得分:4)

您可以这样做:

我已将switchchange上的select事件合并在一起

$("select[name=experience]").on("change", function() {
  var ddate = new Date();

  switch ($(this).val()) {
    case "1-3":
      ddate.setDate(ddate.getDate() + 15);
      break;
    case "3-5":
      ddate.setDate(ddate.getDate() + 30);
      break;
    case "5-8":
      ddate.setDate(ddate.getDate() + 45);
      break;
    case "8-11":
      ddate.setDate(ddate.getDate() + 60);
      break;
    default:
  }

    $(".datavalue").val(ddate)
});

请注意:我已经为您的input添加了一个类,以便更好地选择它

演示

$("select[name=experience]").on("change", function() {
  var ddate = new Date();

  switch ($(this).val()) {
    case "1-3":
      ddate.setDate(ddate.getDate() + 15);
      break;
    case "3-5":
      ddate.setDate(ddate.getDate() + 30);
      break;
    case "5-8":
      ddate.setDate(ddate.getDate() + 45);
      break;
    case "8-11":
      ddate.setDate(ddate.getDate() + 60);
      break;
    default:
  }
  
	$(".datavalue").val(ddate)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-3 form-group ">
  <br>
  <label class="required">A Sample Dropdown when I select the value the date has to automatically get filled in the text box</label> <br><select class="form-control" name="experience" required>
										<option value="">--values--</option>
										<option name="experience" value="0-1">Current date</option>
										<option name="experience" value="1-3">date after 15 days from current date</option>
										<option name="experience" value="3-5">date after 30 days from current date</option>
										<option name="experience" value="5-8">date after 45 days from current date</option>
										<option name="experience" value="8-11">date after 60 days from current date</option>
									</select>
</div><br><br>
<div>
  <input type="text" class="datavalue" />
</div>