auto-populated form with the remaining data from one of the selected fields

Asked

Viewed 55 times

0

I wanted to have a dynamic form where the only thing asked is the selection of 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 organised 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 p to a user-like object that is not visible where it is, but my goal was to get around this problem in some way.

1 answer

0

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

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>
<dl th: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>

Browser other questions tagged

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