How to get values from two html selects in javascript?

Asked

Viewed 691 times

2

Basically I have the code below:

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

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

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

gravar.click(function(){
  
});
<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 value="Clientes">Clientes</option>
        <option value="Boletos">Boletos</option>
        <option value="Usuarios">Usuários</option>
        <option value="Configuracoes">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>
 <button id="gravar" class="btn btn-primary" style="float:right;">Gravar</button>
 <div id="texto">
 </div>

As you can see by executing the code, I pass values(Object) from one checkbox to another and vice versa, I would like that when you click to record I pass the objects of these checkboxes as a List, to be treated in the Controller.

I tried to do the following way, that ends up returning me a List but only comes an object.

var perfisUtilizados = [];
perfisUtilizados = $('#selectPerfisUtilizados').find('option');
var perfisDisponiveis = [];
perfisDisponiveis = $('#selectPerfisDisponiveis').find('option');

gravar..click(function() {
  location.href = '${pageContext.request.contextPath}/permissao/perfis/${id}/' + perfisUtilizados + "," + perfisDisponiveis;
});

And when you click on the record you go to this Controller method:

@Get("/permissao/perfis/{id}/{perfisUtilizados},{perfisDisponiveis}")
public void salvarPerfisDaPermissao(Long id, List<Perfil> perfisUtilizados,
        List<Perfil> perfisDisponiveis){
  //Implementação
}

How to solve?

  • What is the default expected by the server? Comma-separated words? Wouldn’t it be better to send this data in the body of the request?

  • @Nevershowmyface the expected by the server would be 2 Lists of type Profile, this is the object passed in value, above is just an example so that it can be exemplified and can show the functioning, as it would send the data in the body of the request?

1 answer

1


Using jQuery, you can send the permissions lists within the request body in JSON format like this

gravar.click(function() {
  $.ajax({
    headers: {'Content-Type': 'application/json; charset=utf-8'}
    type: 'POST',
    url: url,                                  // Substitua pela URL do sistema
    data: JSON.stringify({
      permissoes: permissoes.find('option').map(function() {
        return this.value;
      }).toArray(),
      minhasPermissoes: minhasPermissoes.find('option').map(function() {
        return this.value;
      }).toArray()
    }),
  }).done(function(response, event_type) {     // Em caso de sucesso
    console.log('done', response, event_type);
  }).fail(function(response, event_type) {     // Em caso de falha
    console.log('fail', response, event_type);
  }).always(function(response, event_type) {   // Depois do sucesso/falha
    console.log('always', response, event_type);
  })
});

Inspect the variables response and event_type, by developer tool, to perform the necessary treatment on the client side.

Since I don’t program in Java I wouldn’t know how the data will be received on the server side but the intention is to send an object with the following pattern:

{
  "permissoes": ["Clientes", "Boletos"],
  "minhasPermissoes": ["Configuracoes", "Usuarios"],
}

Browser other questions tagged

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