Create dynamic form array in PHP

Asked

Viewed 1,232 times

2

Good evening guys. How do I get the information from a form with dynamic inputs in array? Dynamic inputs is when the user clicks on a button asking for more inputs.

1 answer

1


You can do it, I’ll do it with jQuery, add jQuery to your tags sff. You can do it as well as example 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.

Server (PHP) EX:

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

Here we should make validations for each of the names/emails, if only if they are empty and/or undergo some kind of sanitization

Example in jsfiddle

Browser other questions tagged

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