【问题标题】:How to select maximum date from select box show alert message in Js如何从选择框中选择最大日期在Js中显示警报消息
【发布时间】:2018-03-22 17:36:05
【问题描述】:

在下面的 sn-p 中,最大日期为 2017 年 7 月 29 日。如果我选择最大日期,我们应该显示一个警告框。是否可以使用 Javascript 或 jQuery?

注意:选项以随机顺序显示。

HTML:

<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option value="3">10-July-2017</option>
    <option value="12">15-July-2017</option>
    <option value="9">29-July-2017</option>
    <option value="5">23-July-2017</option>
</select>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

你可以试试这样的:

逻辑:

  • 创建一个变量来保存最大日期的值或文本(在下面的示例中)。
  • 然后添加一个 eventListener 来检查必要的属性变化。
  • 如果此属性与步骤 1 中计算的 Max 相同,请提醒用户。

注意:这两种方法都假设没有动态元素,因此最大日期的计算是在 document.ready 上预先完成的。另外,我将value 或text 保留在变量中。这将允许我们绕过为每次更改创建日期的步骤。

使用文本的方法

$(function(){
  var maxValue = null;
  function computeMaxValue(arr){
    arr.reduce(function(_max, cur){
      var t = new Date(cur).getTime();
      if(t > _max) {
        _max = t;
        maxValue = cur;
      }
      return _max;
    }, 0)
  }
  
  var dates = $('#period option').map(function(){ return $(this).text() }).get();
  computeMaxValue(dates);

  $('#period').on('change', function(){
    var text = $('option:selected', this).text();
    if(text === maxValue){
      console.log('You have selected Max value');
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option value="3">10-July-2017</option>
    <option value="12">15-July-2017</option>
    <option value="9">29-July-2017</option>
    <option value="5">23-July-2017</option>
</select>

有价值的方法

$(function(){
  var maxValue = null;
  function computeMaxValue(selector){
    var temp = 0;
    $(selector).each(function (index, el){
      var time = new Date(el.textContent).getTime();
      if(time >= temp) {
        temp = time;
        maxValue = el.value;
      }
    })
  }
  
  computeMaxValue('#period option');

  $('#period').on('change', function(){
    if(this.value === maxValue){
      console.log('You have selected Max value');
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option value="3">10-July-2017</option>
    <option value="12">15-July-2017</option>
    <option value="9">29-July-2017</option>
    <option value="5">23-July-2017</option>
</select>

带有 1 个选项的示例

$(function(){
  var maxValue = null;
  function computeMaxValue(selector){
    var temp = 0;
    $(selector).each(function (index, el){
      var time = new Date(el.textContent).getTime();
      if(time >= temp) {
        temp = time;
        maxValue = el.value;
      }
    })
  }
  
  computeMaxValue('#period option');

  $('#period').on('change', function(){
    if(this.value === maxValue){
      console.log('You have selected Max value');
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option>--Select Period--</option>
    <option value="5">23-July-2017</option>
</select>

【讨论】:

  • 非常感谢。它的工作。我怀疑选择框中是否只有一个日期可用,然后没有显示警报消息。怎么办?
  • 如果您只有1个选项,它将被默认选择。所以改变永远不会触发,所以处理也不会发生。尝试添加 &lt;option&gt;&lt;/option&gt; 作为默认值。
  • 我在选择中添加了
  • 第一次onchange它不起作用,然后第二次改变它的工作。请再次检查代码
【解决方案2】:

将options转为ms,获取最大值,然后检查选择的日期是否与最大值相同。(使用纯js)

var periodSelector = document.getElementById('period');
var options = periodSelector.options;

periodSelector.onchange = function(e) {
  
  // get the selected date and convert it to ms
  var selectedIndex = this.selectedIndex;
  var selectedDate = new Date(options[selectedIndex].text).valueOf();
  
  // convert all date to ms and get the max date
  var maxDate = Array.prototype.reduce.call(options, function(maxValue, curValue) {
    return Math.max(new Date(curValue.text), maxValue);
  }, 0);
  
  // check if selected date is same as max date
  if (selectedDate === maxDate) {
    alert('Max Date is selected');
  }
};
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option value="3">10-July-2017</option>
    <option value="12">15-July-2017</option>
    <option value="9">29-July-2017</option>
    <option value="5">23-July-2017</option>
</select>

【讨论】:

  • 你可以在reduce中实现最大计算。无需再次循环。另外,假设没有动态选项,我们可以预先进行处理并检查值
【解决方案3】:

试试下面的代码:

$("#period").change(function(){
  var selectedValue = $(this).find("option:selected").text();
  var data = selectedValue.split("-");
  var month = new Date(Date.parse(data['1']+data['0'], data['2'])).getMonth();
  var selectedDate = new Date(data['2'],month,data['0']);

  var dates = [];
  $("#period").find("option").each(function(e){
    var currentText = $(this).text();
    var currenData = currentText.split("-");
    var currentMonth = new Date(Date.parse(data['1']+data['0'], data['2'])).getMonth();
    dates.push(new Date(currenData['2'],currentMonth,currenData['0']));
  });
  var maxDate=new Date(Math.max.apply(null,dates));
 if(selectedDate.getTime() === maxDate.getTime()){
    alert(maxDate);
 }
});
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    <option value="3">10-July-2017</option>
    <option value="12">15-July-2017</option>
    <option value="9">29-July-2017</option>
    <option value="5">23-July-2017</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    【解决方案4】:

    希望下面的代码有所帮助

    <!DOCTYPE html>
    <html>
    <head>
        <title> Stack Overflow Question </title>
        <style>
    
        </style>
    </head>
    <body>
    
    	<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
    	    <option value="3">10-July-2017</option>
    	    <option value="12">15-July-2017</option>
    	    <option value="9">29-July-2017</option>
    	    <option value="5">23-July-2017</option>
    	</select>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
          $('#period').on('change',function(){
          	  //Array to Store the dates from the options
          	  var datesArr = [];
              //Get the date from the Selected option
              var d = new Date($('#period option:selected').text()).getDate();
    
              //Pushing the dates to the Array
              $('#period option').each(function(){
              	  var d = new Date($(this).text());
              	  datesArr.push(d.getDate());
              });
              
              //Getting the Max value from the Array
              var max = Math.max(...datesArr);
    
              //Converting to integers
              d = parseInt(d);
              max = parseInt(max);
             
              //Comparing
              if(d == max){
              	 alert("Selected the Maximum Date");
              }
    
    
          });
        </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2020-06-24
      • 2021-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多