How to mount an array of selected select items in html and scroll through it to organize items in javascript?

Asked

Viewed 758 times

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>
<link rel="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>
<div class="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 several items from the first select and click on associate, it switches to the second select the concatenated items, for example: Selecting "Boletos" and "Usuários", and clicking Associating, it fills the second select as an item "Boletosusuários", and wanted to actually fill the select with "Boletos" and then below "Usuários".

I thought of making an array if selected items and go through it and for each selected item gave an append in select, but I do not know how to do this. Some hint of how to be done?

1 answer

1


The result is expected because you capture the text that exists in all elements, but not the elements themselves, and insert it into a new option within 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'));
});

Browser other questions tagged

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