Create array from dynamic form in PHP

2

Good evening guys. How can I get information from a form with dynamic array inputs? The dynamic inputs are when the user clicks a button requesting more inputs.

    
asked by anonymous 21.05.2016 / 04:17

1 answer

1

Can do, I'll do with jQuery, add jQuery to your sff tags. You can do this as below:

HTML:    Add Friends Name / Email:

<form method="POST">
    <div class="campos">
        Nome:<br>
        <input name="nomes[]">
        Email:<br>
        <input name="emails[]">
    </div>
    <input type="submit">
</form>
<button class="add_friend">Adicionar amigo</button>

JQUERY

$('.add_friend').on('click', function(){
    var campos = $('.campos').eq(0).clone(); // copiar só um destes elementos, escolhi copiar o primeiro que é o unico que tenho a certeza que vai sempre existir
    campos.find('input').val(''); // por o valor dos inputs dos novos campos (nome/email) vazios para o caso de termos preenchido já nos primeiros inputs ($('.campos').eq(0))
    $('input[type="submit"]').before(campos);
});

After submitting the form.

EX (PHP) Server:

print_r($_POST['names']); // array('miguel', 'patricia', 'claudia');
print_r($_POST['emails']); // array('[email protected]', '[email protected]', '[email protected]');
//$

Here we should validate for each of the names / emails, even if they are empty and / or undergo some sort of sanitization

Example on jsfiddle

    
21.05.2016 / 05:04