self-populated form with the remaining data of one of the selected fields

0

I wanted to have a dynamic form where the only thing that is asked is to select a user u from a list of users passed to the model from a controller, the email and status fields should be automatically displayed depending on the user who is selected.

The user object has the following class:

public class Utilizador{
  private String perfil;
  private String email;
  private string estado;

  ...
}

The form elements are organized as follows:

<dl th:class="form-group">
  <dt>perfil:</dt>
  <dd>
     <select class="form-control" th:field="*{hhFrom}">
        <option th:each=" u : ${utilizadores}" th:value="" 
             th:text="${u.perfil}">Options
        </option>
     </select> 
  </dd>
  <dt>email:</dt>
  <dd th:text="${u.email}></dd>
  <dt>estado:</dt>
  <dd th:text="${u.estado}></dd>
</dl>

I am aware that th: text="$ {u.email} and th: text=" $ {u.status} are pointing to a user-type object that is not visible where they are, but my goal was to get around this problem in some way.

    
asked by anonymous 20.02.2018 / 01:32

1 answer

0

You can pass the {$ users} to an array (if it is not) and then work with INDEX as an ID using <option value="index">Nome do perfil</option> and then call the change with $('selector').change(function() {...})

It would look like this:

$('document').ready(function () {
  // Apenas para o exemplo
  class Utilizador {
    constructor(perfil, email, estado) {
      this.perfil = perfil;
      this.email = email;
      this.estado = estado;
    }
  }

  var utilizadores = Array(2); // Array com os utilizadores
  utilizadores[0] = new Utilizador("Fulano", "[email protected]", "SP");
  utilizadores[1] = new Utilizador("Ciclano", "[email protected]", "RJ");
  // Apenas para o exemplo

//Loop no array para criar um option com value=(INDEX do array) e com texto=(Perfil)
  for (var i = 0; i < utilizadores.length; i++) {
    $('#perfil').append("<option value=" + i + ">" + utilizadores[i].perfil + "</option>");
  }

//Buscar o utilizador pelo INDEX do array
  function updateFields(i) {
    if (i == -1) {
      $('#email').text("");
      $('#estado').text("");
    } else {
      $('#email').text(utilizadores[i].email);
      $('#estado').text(utilizadores[i].estado);
    }
  }

  $('#perfil').change(function () {
    var i = $(this).find(":selected").val(); // i = value do option selectionado
    updateFields(i);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><dlth:class="form-group">
  <dt>perfil:</dt>
  <dd>
     <select class="form-control" th:field="*{hhFrom}" id="perfil">
	 <option value="-1">Selecione um perfil</option>
     </select> 
  </dd>
  <dt>email:</dt>
  <dd id="email"></dd>
  <dt>estado:</dt>
  <dd id="estado"></dd>
</dl>
    
21.02.2018 / 02:29