Javascript - Prevent select option from select smaller than another

0

Hello.

I'm making a system for scheduling by schedule. I have 2 select's: start and end.

I need a function to prevent the end time, can not be less than the start + 3. Ex: start = 10, the end must be at least 13, and do not let it select 12 or less.

Below what I have already:

<div>
<select id="inicio" onchange="horainicio()">
<option value="9">9:00</option>
<option value="10">10:00</option>
<option value="11">11:00</option>
<option value="12">12:00</option>
<option value="13">13:00</option>
<option value="14">14:00</option>
<select>

<select id="fim" onchange="horafim()">
<option value="12">12:00</option>
<option value="13">13:00</option>
<option value="14">14:00</option>
<option value="15">15:00</option>
<option value="16">16:00</option>
<option value="17">17:00</option>
<select>
Resultado:<br/>
<input type="text" id="resultado">
<button type="button" onclick="calcular()">Calcular</button>
</div>
<script>

function horainicio() {
var resultado = document.getElementById("resultado");
document.getElementById("fim").value = parseInt(inicio) + 3;
resultado.value = document.getElementById("fim").value-document.getElementById("inicio").value;
}

function horafim(){
resultado.value = document.getElementById("fim").value-document.getElementById("inicio").value;
}
</script>

Thank you!

    
asked by anonymous 12.05.2017 / 18:56

1 answer

0

As the friend @Sergio commented, if you state the conditions, say what should happen, the answer may be more precise, but this validation can be done in a very simple way, if the value of the initial time + 3 is greater that the value of the selected end time, does whatever you want (block, etc.)

var horaIni = parseInt(document.getElementById("inicio").value);
var horaFim = parseInt(document.getElementById("fim").value);
if(horaIni + 3 > horaFim){
  //...
}

The following is a snippet with an example (if it is not a valid time, I leave the select blank):

function horafim(value) {
  var horaIni = parseInt(document.getElementById("inicio").value);
  var horaFim = parseInt(value);
  if (horaIni + 3 > horaFim) {
    alert("Hora inválida.");
    document.getElementById("fim").value = "";
  }
}
<div>
  <select id="inicio">
<option value="9">9:00</option>
<option value="10">10:00</option>
<option value="11">11:00</option>
<option value="12">12:00</option>
<option value="13">13:00</option>
<option value="14">14:00</option>
<select>

<select id="fim" onchange="horafim(value)">
<option value="12">12:00</option>
<option value="13">13:00</option>
<option value="14">14:00</option>
<option value="15">15:00</option>
<option value="16">16:00</option>
<option value="17">17:00</option>
<select>
</div>
    
12.05.2017 / 19:29