0

I have some time instances In select option. I want the user to give his specifications by 6:00 am if he wants to use the system at 10:00 am i.e. there should be 4 hours gap. So after 6.00 am the option of 10.00 am should be disabled, after 6.30 am, the option of 10.00 am and 10.30 am should be disabled and so on.. Here is my code-

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

</head>
<input type="date" name="Date" id = "put_date" required>
<select name="Time" id = "time">
<option value="Select Time" id = time>Select Time</option>
<option value="10.00.00" id = t1> 10.00.00</option>
<option value="10.30.00" id = t2>10.30.00</option>

</select>
<script>
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var dd = today.getDate();
var mm = today.getMonth()+1; 
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
} 

if(mm<10) {
mm = '0'+mm
} 

var today_date = dd + '-' + mm + '-' + yyyy;
if((document.getElementById("put_date") == today_date) && (h==5) && (m==59) 
&& (s==59))
{
document.getElementById("t1").disabled = true;
}
</script>
</div>
</html>

There is no syntax error or any other sort of error being shown when the program is run. But I am not getting the desired output.

please someone guide me where I am wrong.

Thanks!

Shivam Pande
  • 184
  • 2
  • 14
  • You cannot compare dates that way. You do NOT have a `` tag in your html, you need an event listener for the change as users input values - it will be blank initially as you have written it here. – Mark Schultheiss Feb 14 '18 at 18:12
  • What should happen if a user entered a past date say last week? What should happen if a time boundary changes (user sits looking at the screen while time passes). – Mark Schultheiss Feb 14 '18 at 18:23

3 Answers3

1

var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var dd = today.getDate();
var mm = today.getMonth()+1; 
var yyyy = today.getFullYear();
var strNow=h + m/100;
$("#time").children().each(function() {
    var strOpt=parseFloat($(this).attr("value").split(".")[0]) + parseFloat($(this).attr("value").split(".")[1])/100;
    if (strNow+4 > strOpt) {
        $(this).prop("disabled", "true");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" name="Date" id="put_date" required/>
<select name="Time" id="time">
<option value="Select Time">Select Time</option>
<option value="10.00.00" disabled>10.00.00</option>
<option value="10.30.00">10.30.00</option>
<option value="11.00.00">11.00.00</option>
<option value="11.30.00">11.30.00</option>
<option value="12.00.00">12.00.00</option>
<option value="12.30.00">12.30.00</option>
<option value="13.00.00">13.00.00</option>
<option value="13.30.00">13.30.00</option>
<option value="14.00.00">14.00.00</option>
<option value="14.30.00">14.30.00</option>
<option value="15.00.00">15.00.00</option>
<option value="15.30.00">15.30.00</option>
<option value="16.00.00">16.00.00</option>
<option value="16.30.00">16.30.00</option>
<option value="17.00.00">17.00.00</option>
<option value="17.30.00">17.30.00</option>
<option value="18.00.00">18.00.00</option>
<option value="18.30.00">18.30.00</option>
<option value="19.00.00">19.00.00</option>
<option value="19.30.00">19.30.00</option>
<option value="20.00.00">20.00.00</option>
<option value="20.30.00">20.30.00</option>
<option value="21.00.00">21.00.00</option>
<option value="21.30.00">21.30.00</option>
</select>
MBJH
  • 1,571
  • 3
  • 17
  • 36
  • While this strictly works on page render (I up voted for that) this would be invalid if a time boundary was crossed (user sat looking at it as time passed) prior to the user entering a value (selecting a time) Note the unspecified (by the OP) way to handle this makes this a valid answer.. – Mark Schultheiss Feb 14 '18 at 18:19
0

I was drawn back to this to illustrate how to compare actual time component of a date. To do this I generated a list of select options with the time component as the value, one for each half hour period. I then set up a timer to alter the select list, making options disabled once a time has elapsed based upon the current users browser. Technically you would want to use a server date/time as the start point instead of the browser as users could simply reset their local time to "cheat" this but we will ignore that for now.

Given that, this solution does not perfectly match the question, it uses a more conventional time display HH:MM such as 10:30 AM (local times for the users). With a large number of available options (48) and the likely circumstance that users will have a number at the start of the select list disabled, it at least to me, makes sense to attempt to reduce that list in the UI so I simply attempted to hide options that are disabled using CSS. Other options such as removal from the list may be better. I also added date validation on a change event but that is not strictly needed but illustrates more of a "solution".

Illustrated examples:

  • A timer to check and if a 30 minute time boundary is crossed, disable appropriate options. I check this every second but you COULD set the timer to only check it AT the time boundary. I also execute the countdown to that 30 minute boundary.
  • Date validation - check that it IS a date. Perhaps also force users to enter a "future" date - since a request for yesterday or last week also seems like an invalid one in this use case.
  • Added a time is up (timesup) custom event to trigger on each countdown expiration. Since we have this, we can trigger it on initial startup as well with sel.dispatchEvent(timesup);

// create a timer to use on each 30 minute time elapse (from here: https://stackoverflow.com/a/20618517/125981 )
function CountDownTimer(duration, granularity) {
  this.duration = duration;
  this.granularity = granularity || 1000;
  this.tickFtns = [];
  this.running = false;
}
CountDownTimer.prototype.start = function() {
  if (this.running) {
    return;
  }
  this.running = true;
  var start = Date.now(),
    that = this,
    diff, obj;

  (function timer() {
    diff = that.duration - (((Date.now() - start) / 1000) | 0);

    if (diff > 0) {
      setTimeout(timer, that.granularity);
    } else {
      diff = 0;
      that.running = false;
    }

    obj = CountDownTimer.parse(diff);
    that.tickFtns.forEach(function(ftn) {
      ftn.call(this, obj.minutes, obj.seconds);
    }, that);
  }());
};
CountDownTimer.prototype.onTick = function(ftn) {
  if (typeof ftn === 'function') {
    this.tickFtns.push(ftn);
  }
  return this;
};
CountDownTimer.prototype.expired = function() {
  return !this.running;
};
CountDownTimer.parse = function(seconds) {
  return {
    'minutes': (seconds / 60) | 0,
    'seconds': (seconds % 60) | 0
  };
};
// dynamically add the select values
function generateSelects(step, element) {
  var dt = new Date(1970, 0, 1, 0, 0, 0, 0);
  // empty out the select options
  while (element.firstChild) {
    element.firstChild.remove();
  }
  var firstoption = document.createElement("option");
  firstoption.innerText = "Select Time";
  firstoption.value = "Select Time";
  element.appendChild(firstoption);

  while (dt.getDate() == 1) {
    let point = dt.toLocaleTimeString('en-US');
    let pointValue = dt.getTime();

    let item = document.createElement("option");
    item.value = pointValue;
    item.innerText = point;
    element.appendChild(item);
    // increment for next step
    dt.setMinutes(dt.getMinutes() + step);
  }
}

window.onload = function() {
  generateSelects(checkperiod, document.getElementById("timeselect"));
  sel.dispatchEvent(timesup);
  //console.clear();
  // var minutes = checkperiod;
  // var seconds = minutes * 60;
  //var desiredBoundryMintues = checkperiod;
  var mytimer = startTimer(details);
};

function secondsToNext(intervalminutes) {
  var current = new Date();
  var min = current.getMinutes();
  min = min > intervalminutes ? min - intervalminutes : min;
  // min to next interval
  min = (60 - (min + intervalminutes));
  // seconds to next interval
  var seconds = min * 60;
  // minutes to next (in seconds) less current seconds in the minute get total seconds to next interval
  seconds = seconds + (60 - current.getSeconds());
  return seconds;
}

function startTimer(p) {
  //console.log(p);
  var display = document.querySelector('#timerdisplay');
  var s = secondsToNext(p.detail.period);
  var timer = new CountDownTimer(s);
  // to test: var timer = new CountDownTimer(6);
  timer.onTick(format).onTick(restart).start();

  //allows us to restart time at defined (30) interval minute mark
  function restart() {
    if (this.expired()) {
      mydate.dispatchEvent(timesup);
      this.duration = (p.detail.period * 60) - 1;
      this.duration = secondsToNext(p.detail.period);
      setTimeout(function() {
        timer.start();
      }, 1000);
    }
  }

  function format(minutes, seconds) {
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    // show progress on each tick
    display.textContent = minutes + ':' + seconds;
  }

};
// check if is valid date
// credit here: https://stackoverflow.com/a/1353711/125981
function isDate(d) {
  if (Object.prototype.toString.call(d) === "[object Date]") {
    // it is a date
    if (isNaN(d.getTime())) { // d.valueOf() could also work
      // date is not valid
      return false;
    } else {
      // date is valid
      return true;
    }
  } else {
    // not a date
    return false;
  }
}
// parse a date in mm/dd/yyyy format
function parseDate(input) {
  // assume / or - for delimiters
  var parts = input.indexOf("/") !== -1 ? input.split('/') : input.split('-');
  return new Date(parts[2], parts[0] - 1, parts[1]); // Note: months are 0-based
}
function checkSelectOptions(e) {
  //console.dir(e);
  var today = new Date();
  var dt = new Date(1970, 0, 1, 0, 0, 0, 0);
  dt.setHours(today.getHours() + e.detail.hour);
  var nowtime = dt.getTime();
  var myOpts = e.target.getElementsByTagName("option");
  for (var i = 0; i < myOpts.length; i++) {
    myOpts[i].disabled = (myOpts[i].value <= nowtime);
  }
}

function checkSelect(e) {
  var dt = new Date(1970, 0, 1, 0, 0, 0, 0);
  dt.setTime(e.target.value);
  document.getElementById("showtime").innerHTML = dt.toLocaleTimeString('en-US');
}

function checkDate(e) {
  var d = parseDate(e.target.value);
  var isValidDate = isDate(d);
  document.getElementById("showdate").innerHTML = isValidDate ? d.toLocaleDateString('en-US') : "Invalid Date entered";
}

// horrid global variables
var checkperiod = 30; //minute boundary
var boundaryHour = 4;

// create event
//var timesup = new Event('timesup');
var details = {detail:{"period":checkperiod,"hour":boundaryHour }};
var timesup = new CustomEvent('timesup',  details);
///var timesup = document.createEvent('Event');
// Define event named 'timesup'.
///timesup.initEvent('timesup', true, true);

var mydate = document.getElementById("put_date");
mydate.addEventListener('change', checkDate);

var sel = document.getElementById("timeselect");
sel.addEventListener('change', checkSelect, false);
sel.addEventListener('timesup', checkSelectOptions, false);
option:disabled {
  display: none;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<div>
  <input type="date" name="Date" id="put_date" required>
  <select name="timeselect" id="timeselect">
    <option value="Select Time">Select Time</option>
</select>
  <div>Next selection window closes in <span id="timerdisplay"></span> minutes!</div>
  <div>You chose: <span id="showtime">no time yet</span></div>
  <div>You chose Date: <span id="showdate">no date yet</span></div>
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
-1

The jQuery way to do this is

$("#t1").prop("disabled", true);
user9263373
  • 1,054
  • 8
  • 15
  • I see it now... you have to enclose your id attribute in quotes. So change ` – user9263373 Feb 14 '18 at 16:14
  • @user9263373 Note it is perfectly valid to NOT enclose an id in quotes. Debatable if this is a good idea but not the issue here.https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute – Mark Schultheiss Feb 14 '18 at 18:10