How to display two Textbox from a result in the Dropdownlist

Asked

Viewed 67 times

0

I display a Dropdownlist with two SC and PR values, if it selects SC then I want it to display two Textbox, one with the RG, and one with the Date of Birth, and if the person selects PR, I want to go down only one field with the Date of Birth and it cannot be minor.

I’m doing it in C# MVC, and I have a question of how to do it in Jquery, Javascript, or other solution.

1 answer

0


Assuming you already have jquery embedded in your page.

The fields:

<select name="campoSelecao" id="campoSelecao">
  <option value="SC">SC</option>
  <option value="PR">PR</option>
</select>
<input type="text" name="inputRg" id="inputRg" style="display: none">
<input type="text" name="inputDtNascimento" id="inputDtNascimento" style="display: none">

File . js

$('body').on('change', '#campoSelecao', function () {
            $('#inputRg').css('display','none');
            $('#inputDtNascimento').css('display','none');

            var valorSelecionado = $(this).val();
            if (valorSelecionado == 'SC') {
                $('#inputRg').css('display','block');
                $('#inputDtNascimento').css('display','block');
            }

            if (valorSelecionado == 'PR') {
                $('#inputDtNascimento').css('display','block');
            }
    });

To check age:

1 - I suggest using a date plugin, for example: https://jqueryui.com/datepicker/ .With this plugin implemented, we will have the date field formatted;

2 - Add the plugin Moment.js https://momentjs.com/ . This plugin will make any comparison easier;

3 - Implement the rule in your file . js

$('body').on('focusout', '#inputDtNascimento', function () {
   var nascimento = $(this).val(); //pega a valor do campo data
   var idade = Math.floor(moment(new Date()).diff(moment(nascimento), 'years', true));
   if (idade < 18) {
      $(this).focus(); //da o foco no campo
      $(this).val(''); //limpar o campo
   }
});

Browser other questions tagged

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