How to mount an array of select items from select in html and run it to organize items in javascript?

2

I have the code:

var associar = $("#associar");
var desassociar = $("#desassociar");
var permissoes = $("#permissoes");
var minhasPermissoes = $("#minhasPermissoes");

associar.click(function() {
  var selecionado = permissoes.find('option:selected');
  minhasPermissoes.append('<option>' + selecionado.text() + '</option>');
  selecionado.remove();
});

desassociar.click(function() {
  var selecionado = minhasPermissoes.find('option:selected');
  permissoes.append('<option>' + selecionado.text() + '</option>');
  selecionado.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script><divclass="container">
  <div class="row">
    <div class="col-md-6">
      <label>Permissões</label>
      <select id="permissoes" class="form-control" multiple>
        <option>Clientes</option>
        <option>Boletos</option>
        <option>Usuários</option>
        <option>Configurações</option>
      </select>
    </div>
    <div class="col-md-6">
      <label>Minhas Permissões</label>
      <select id="minhasPermissoes" class="form-control" multiple>
      </select>
    </div>
  </div>
  <br>
  <button id="associar" class="btn btn-primary">Associar</button>
  <button id="desassociar" class="btn btn-primary">Desassociar</button>

</div>

As you can see, when we select multiple items from the first select and click on associate, it goes to the second select the concatenated items, for example: Selecting "Tickets" and "Users", and clicking on Associate, it fills the second select as a "UserBills" item, and wanted to actually fill the select with "Tickets" and below "Users".

I thought of making an array if selected items and traversing it and for each selected item gave an append in select, but I do not know how to do that. Any tips on how to get done?

    
asked by anonymous 24.02.2016 / 18:12

1 answer

1

The result is expected because you capture text that exists in all elements, but not the elements themselves, and inserts a new option into the "My Permissions" list. The correct JavaScript code would be

var associar = $("#associar");
var desassociar = $("#desassociar");
var permissoes = $("#permissoes");
var minhasPermissoes = $("#minhasPermissoes");

associar.click(function() {
  minhasPermissoes.append(permissoes.find('option:selected'));
});

desassociar.click(function() {
  permissoes.append(minhasPermissoes.find('option:selected'));
});
    
24.02.2016 / 18:25