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

Asked

Viewed 1,385 times

2

I’m creating an html site and I’m kind of a beginner yet. I’m doing an establishment registration screen. My problem is: when selecting a radio button, I want you to change the select data (combobox). Example: Radio Button Institution, I want you to show in select (Normal, technical or higher), if you change option, as General change select to parks, shopping and etc Ever since I thank.

1 answer

5


That’s simple:

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

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

Below you have a JSON that configures the different possibilities of option select, which is mounted at the time 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
  <input type="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: https://jsfiddle.net/ksLoapde/1/

Browser other questions tagged

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