1

In the below snippet, the maximum date is 29-July-2017. If I select the maximum date we should display an alert box. Is it possible using Javascript or jQuery?

Note: Options display in random order.

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>
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
Param
  • 77
  • 1
  • 2
  • 9

4 Answers4

2

You can try something like this:

Logic:

  • Create a variable that will either hold value or text(in below sample) of max date.
  • Then add an eventListener to check the necessary attribute on change.
  • If this attribute is same as Max computed in step 1, alert the user.

Note: Both the approaches assumes that there will be no dynamic elements and so the computation of max date is done beforehand on document.ready. Also, I'm keeping value or text in variable. This will allow us to bypass the step to create date on every change.

Approach with 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>

Approach with Value

$(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>

Sample with 1 option

$(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>
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • thanks you so much. Its working. I have one doubt if there is only one date available in select box then no alert message displayed. How to do? – Param Oct 11 '17 at 07:33
  • If you have only 1 option, it will be selected as default. So change will never fire and so processing will not happen. Try adding `` as a default value. – Rajesh Oct 11 '17 at 07:35
  • I have added – Param Oct 11 '17 at 07:52
  • First time onchange its not working, then second time change its working. Kindly gothrough code again – Param Oct 11 '17 at 09:37
1

Turn options into ms and get the max value, then check if the selected date is as same as the max value.(use pure 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>
Rajesh
  • 24,354
  • 5
  • 48
  • 79
Rex Hsu
  • 464
  • 2
  • 7
  • 1
    You can achieve the max computation in reduce. No need to loop again. Also, assuming there will be no dynamic options, we can do processing beforehand and just check value – Rajesh Oct 11 '17 at 07:21
1

Hope the below code helps

<!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>
yasarui
  • 6,209
  • 8
  • 41
  • 75
1

Try Below Code:

$("#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>
JavidRathod
  • 483
  • 2
  • 10