How to do a Jquery that when selecting a radio button, I change the items of a select?

2

I'm creating an html site and I'm still a bit new to it. I'm doing a store registration screen. My problem is: when selecting a radio button, I want it to change the select (combobox) data. Example: Radio Button Institution, I want it to show in the select (Normal, technical or higher), if change of option, as General change the select to parks, purchases and etc. Thanks in advance.

    
asked by anonymous 04.05.2016 / 23:00

1 answer

5

This is simple:

$('input').on('change', function() {
    $('select').val(this.value);
});

As your question has no code to exemplify I leave a generic example. Using $('select').val(this.value); you are telling select to choose option whose value is this.value . The this.value in this function is value of the input.

Below you have a JSON that sets up the different possibilities of the option of the select, which is set at the moment of choosing the input.

The code I used was this:

var opcoes = {
  instituicao: {
    values: ['normal', 'tecnico', 'superior'],
    html: ['Normal', 'Técnico', 'Superior']
  },
  hospital: {
    values: ['clinica', 'particular', 'hospital'],
    html: ['Clínica', 'Particular', 'Hospital']
  },
  geral: {
    values: ['bar', 'parques', 'compras'],
    html: ['Bar', 'Parques', 'Compras']
  }
};
var $select = $('select#tipos');
$('input').on('change', function() {
  var options = opcoes[this.value]; // ler o valor do input e usá-lo como chave do objeto de opções
  if (options) $select.html(''); // esvaziar o select caso haja conteudo
  options.values.forEach(function(value, i) {
    var el = $('<option/>', { // criar um novo elemento
      value: value, // dar-lhe um value
      html: options.html[i] // dar-lhe um texto 
    });
    $select.append(el); // inserir no select
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label>Instituição<inputtype="radio" name="tipos" value="instituicao" checked>
</label>
<label>Hospital
  <input type="radio" name="tipos" value="hospital">
</label>
<label>Geral
  <input type="radio" name="tipos" value="geral">
</label>

<select name="" id="tipos">
  <option value="normal">Normal</option>
  <option value="tecnico">Tecnico</option>
  <option value="superior">Superior</option>
</select>

jsFiddle: link

    
05.05.2016 / 04:00