Javascript dates

8

Good morning, I had the following question, can it be done that when a input type="date "have passed more than 65 years difference between today's date and the one put by the users, a input type="radio" will be deactivated?

That is, first of all I need to take the value from the "date" field, and then subtract from today's date the date entered, and if it gives more than 65 years apart, that a radio type field is deactivated, Would that be possible?

    
asked by David 26.10.2016 в 10:59
source

2 answers

15

There you have the HTML and Javascript code. I think it's clear but if you have doubts, ask ^^

Instead of a button, you can make an OnChange event of type="date"

The calculation that appears in the IF is because the result gives it to you in milliseconds and it happens to years.

function bloquearRadio(){

    var fechaInput = new Date(document.getElementById("fecha").value); 
    var dateNow = Date.now();
    if((dateNow - fechaInput)/(1000 * 3600 * 24*365) > 65 ){
    //alert("+65");
        document.getElementById("radio").disabled = true;
    }else{
        document.getElementById("radio").disabled = false;
    }
}
<form >
  Fecha:
  <input id="fecha" type="date" >
  <input onclick=bloquearRadio() type="button" value="Validar Fecha">

  <input id="radio" type="radio" >No activo para más de 65 años </input>

</form>
    
answered by 26.10.2016 / 12:04
source
7

The JavaScript code (with some jQuery ) would be as follows:

$(document).ready(function() {document  
  $("#comprobar").on("click", function(e){
    e.preventDefault();
    var hoy = new Date();
    var fecha_introducida = $("input[name='fecha']").val();
    fecha_introducida = new Date(fecha_introducida);
    diferencia = hoy.getFullYear() - fecha_introducida.getFullYear();
    alert("Diferencia de años: "+diferencia);

    if (diferencia > 65){
      $('input[name=radioB]').attr('disabled',true);
    }
  }); 
});
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>

<form id="fecha_input">
    <input type="date" name="fecha">
    <input name="radioB" type="radio"> Menos de 65 años de diferencia<br>
    <button id="comprobar">Comprobar</button>
</form>

To load jQuery in your document, do not forget to add it to the <head>

tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

If you do not understand any part of the code do not hesitate to ask.

    
answered by 26.10.2016 в 12:20