Can you work with data groups in form html?

0

I have the following scenario: The client chooses more than one benefit package on a page (html form), so far so good, working with array

Example:

<input type="checkbox" name="pacote[]" value="pacote1">
<input type="checkbox" name="pacote[]" value="pacote2">

But on a next screen he should put the name of the beneficiaries in each package, which may or may not repeat the same beneficiary for one or more packages.

The structure would look something like this:

Package 1:

  Beneficiário-1
  Beneficiário-2
  Beneficiário-3

Package2:

  Beneficiário-1
  Beneficiário-3
  Beneficiário-4

See that Package2 has a payee that does not repeat in Package1.

When I send the form I have to know which payee is from each package. I'm breaking my head on a way to do this. If you could send more than one form at a time beauty, or if you could do a grouping with <fieldset> would solve it, it would put a hidden field and kill it.

If someone understands the need and can give you some idea, it will be very welcome.

    
asked by anonymous 07.06.2016 / 01:36

1 answer

1

The solution that I see clearest for you would be to create custom elements with JavaScript. As for the question of translating this into data, I did the script below, which translates the HTML structure to JS. See if it helps:

$("form.pacotes").on("submit", function(e) {
  // para evitar que o form seja enviado da maneira padrão
  e.preventDefault();
  var data = [];
  
  // procurar elementos com atributo data-pacote e iterar
  $(this).find("[data-pacote]").each(function(){
    pacote_element = $(this);
    data.push({
        pacote: $(this).attr("data-pacote"),
      
        // o bloco (function(){})() pode parecer estranho, mas funciona como função anônima, um bloco que se auto-executa e apenas retorna o resultado
        beneficiarios: (function(){
            // buscando os ids dos beneficiarios
            var beneficiarios = [];
            pacote_element.find("[data-beneficiario]").each(function(){
                beneficiarios.push($(this).attr("data-beneficiario"));
            });
            return beneficiarios;
        }).call()
    });
  })
  
  // fazendo um output disso
  console.log(data);
  
  // Aqui você pode fazer o envio desses dados por xmlHttpRequest, $.ajax, etc. 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formclass="pacotes">
  <ul data-pacote="1">
    <li data-beneficiario="1">1</li>
    <li data-beneficiario="2">2</li>
    <li data-beneficiario="3">3</li>
    <li data-beneficiario="7">7</li>
    <li data-beneficiario="9">9</li>
    <li data-beneficiario="10">10</li>
  </ul>

  <ul data-pacote="2">
    <li data-beneficiario="4">4</li>
    <li data-beneficiario="5">5</li>
    <li data-beneficiario="6">6</li>
    <li data-beneficiario="8">8</li>
  </ul>
  <button type="submit">Enviar</button>
</form>
    
07.06.2016 / 13:24