如何在输入中添加多个字符串?

时间:2018-06-28 23:15:00

标签: javascript jquery twitter-bootstrap

我正在运行bootstrap datepicker,它具有嵌入式日历和日期范围。以下内容以突出显示前端按钮的方式起作用,但是输入未显示值范围`。

注意,我希望像2014, 2018那样用逗号分隔年份,而我们只能根据范围选择最长两年。

$('#sandbox-container').datepicker({ 
  format: "yyyy", 
  startView: 1, 
  viewMode: "years", 
  minViewMode: "years", 
  minViewMode: "years", 
  multidate: true, 
  multidateSeparator: ", ", 
  autoClose: true, 
}).on("changeDate",function(event){ 
  var dates = event.dates, elem = $('#sandbox-container'); 
  if(elem.data("selecteddates") == dates.join(",")) return; //To prevernt recursive call, that lead to lead the maximum stack in the browser. 
  if(dates.length>2) dates=dates.splice(dates.length-1); 
  dates.sort(function(a,b){return new Date(a).getTime() - new Date(b).getTime()}); 
  elem.data("selecteddates",dates.join(",")).datepicker('setDates', dates); 
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>

<div id="sandbox-container"></div> 
<input type="text" id="date" value="">

1 个答案:

答案 0 :(得分:0)

您没有在“日期​​”输入字段上设置值。您正在“ sandbox-container” div上进行设置。将其更改为输入字段,它将开始填充文本字段。

另外,我还要检查引导程序datepicker日期范围的文档:https://bootstrap-datepicker.readthedocs.io/en/v1.7.1/markup.html#daterange

在这里,我对JS(引用日期元素和调用datepicker show方法)和HTML(已删除的沙箱容器)进行了一些调整

$('#date').datepicker({ 
  format: "yyyy", 
  startView: 1, 
  viewMode: "years", 
  minViewMode: "years",
  multidate: true, 
  multidateSeparator: ", ", 
  autoClose: false,
}).on("changeDate",function(event){ 
  var dates = event.dates, elem = $('#date');
  if(elem.data("selecteddates") == dates.join(",")) 
  	return; //To prevernt recursive call, that lead to lead the maximum stack in the browser. 
  if(dates.length>2)
  	dates=dates.splice(dates.length-1); 
  dates.sort(function(a,b){return new Date(a).getTime() - new Date(b).getTime()}); 
  elem.data("selecteddates",dates.join(",")).datepicker('setDates', dates);
});
$("#date").datepicker("show");
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet" type="text/css" media="screen">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>


<input type="text" id="date" value="">