Creating getFullYear with javascript

Asked

Viewed 37 times

0

Good afternoon guys. See if you can help me with something.

I need to generate a data list. Manufacturing Year and Model Year.

I did it this way:

var i;
for (i = new Date().getFullYear(); i >= 1900; i--)
{

  $('#ano_fabricacao').append("<option value="+i+">"+i+"</option>");
  $('#ano_modelo').append("<option value="+i+">"+i+"</option>");
}

$('#ano_fabricacao').change(function() {
  var ano = $(this).val();
  $('#ano_modelo').find('option').remove();
  $('#ano_modelo').append('<option value="">Até</option>');
  for (i = new Date().getFullYear(); i >= ano; i--)
  {
    $('#ano_modelo').append("<option value="+i+">"+i+"</option>");
  }
});

When selecting the year of manufacture, in the year of the model appears only the following years. Example: I selected 2018 in manufacturing and the model year appears only, 2018, 2019 and 2020 which are the following years. That’s all well and good. But I would like a change. When selecting the year 2015 (in manufacturing) I would like it to appear only 2015 and 2016 (in model). It would only be the following year.

Someone can help?

1 answer

0


I think you got a little lost in the code when you inserted a for at the event change of select of manufacturing year making it difficult to control the years, in the example I did below I didn’t even use it, just entered in the year select of the model a option with the selected year itself and another option which caught the next year by just catching the selected year by making the conversion to Number adding more 1 and storing this in a variable:

for (let i = new Date().getFullYear(); i >= 1900; i--) {
  $('#ano_fabricacao').append("<option value="+i+">"+i+"</option>");
  $('#ano_modelo').append("<option value="+i+">"+i+"</option>");
}

$('#ano_fabricacao').change(function() {
  var ano = $(this).val();
  var anoSeg = Number(ano) + 1;            // ano escolhido + 1

  $('#ano_modelo').find('option').remove();
  $('#ano_modelo').append('<option value="">Até</option>');

  $('#ano_modelo').append("<option value="+ano+">"+ano+"</option>");
  $('#ano_modelo').append("<option value="+anoSeg+">"+anoSeg+"</option>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="ano_fabricacao">
  <option value="0" selected disabled>Selecione</option> 
</select>

<select id="ano_modelo">
  <option value="0" selected disabled>Selecione</option> 
</select>

  • Truth @Leandrade don’t know why I put that other one inside the change. But thanks for the help. It helped a lot!

  • Cool that helped man, success!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.