If the select option is selected, then another option is added?

Asked

Viewed 45 times

0

I have this code here: https://jsfiddle.net/pedroguilherme/ka80cruz/2/

js

var cidades = [
    'São Paulo',
    'Rio de Janeiro',
    'Bahia'];

cidades.forEach(function(item){
    $('#cidades').append('<option>' + item + '</option>');
});


var test = [
    'Test1',
    'Test2',
    'Test3'];

test.forEach(function(item){
    $('#test').append('<option>' + item + '</option>');
});

html

<select id="cidades" class="cidades"></select>
<select id="test" class="test"></select>

Important I want when selecting the Sao Paulo option to include only within the other select... which is the select with id test a Test option 1.

And I want to select the option Rio de Janeiro include only within the other select... which is the select with id test a option Test 2.

And I want to select the option Porto Alegre include only within the other select... which is the select with id test a option Test 3.

  • Append doesn’t solve,
  • I can’t do it via foreach,
  • I tried map and could not.
  • I tried : select with change did not work.
  • I tried change, "click", one etc did not work.

Returning.... :)

I wanted to do it like this

$('#saopaulo').change(function() {
      $("#test1").html('<option>Menino Jesus</option>');
});

 $('#riodejaneiro').change(function() {
      $("#test2").html('<option>CDF Master</option>');
});

 $('#portoalegre').change(function() {
      $("#test3").html('<option>Ethos</option>');
});

1 answer

0


If I understood the purpose correctly, you could put a value in the select options of cities with indexes (index):

cidades.forEach(function(item, index){
    $('#cidades').append('<option value="'+ index +'">' + item + '</option>');
});

And then pick up the item in the array test according to the value of value selected in select:

$('#cidades').change(function() {
   $("#test").html('<option>'+  test[$(this).val()] +'</option>');
});

Behold:

var cidades = [
    'São Paulo',
    'Rio de Janeiro',
    'Bahia'];

cidades.forEach(function(item, index){
    $('#cidades').append('<option value="'+ index +'">' + item + '</option>');
});


var test = [
    'Test1',
    'Test2',
    'Test3'];

test.forEach(function(item, index){
    $('#test').append('<option value="'+ index +'">' + item + '</option>');
});

$('#cidades').change(function() {
   $("#test").html('<option>'+  test[$(this).val()] +'</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="cidades" class="cidades"></select>
<select id="test" class="test"></select>

  • You can use without value tb, but not with id.

  • Without value you would take the option index and take the same index as the other array.

  • In my answer, just change the test[$(this).val()] for test[$("option:selected", this).index()].

Browser other questions tagged

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