0


I want to create a dynamic form to create users, with a "Add user" button that creates new inputs for another user.

$('#add-user').click(function() {
  $(this).before(
    '<input type="text" placeholder="Username">' +
    '<input type="text" placeholder="Email">' +
    '<br>'
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form>
  <input type="text" placeholder="Username">
  <input type="text" placeholder="Email">
  <br>
  
  <button type="button" id="add-user">Add user</button>
  <button type="submit">Create users</button>
</form>

I want the form data structured this way server-side (I am using PHP with Laravel):

$users = [
    [
        'username' => 'toto',
        'email'    => '[email protected]',
    ],
    [
        'username' => 'titi',
        'email'    => '[email protected]',
    ],
    [
        'username' => 'tata',
        'email'    => '[email protected]',
    ]
]

I can't work out how I should name my inputs in order to do that. I know I must use the array names like this name="user[]", but I am stuck.

2
  • 1
    you didn't specified a programming language, are you trying it on JS or PHP? Commented Sep 16, 2019 at 17:00
  • I am using PHP with Laravel. But my problem is client-side in HTML. What value must I give to the name attribute of my inputs? Commented Sep 16, 2019 at 17:32

1 Answer 1

1

As you say, you need to make them like name="user[]". I've made the small changes to your example below:

$('#add-user').click(function() {
  $(this).before(
    '<input type="text" placeholder="Username" name="Username[]">' +
    '<input type="text" placeholder="Email" name="Email[]">' +
    '<br>'
  );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form action="https://httpbin.org/post" method="post">
  <input type="text" placeholder="Username" name="Username[]">
  <input type="text" placeholder="Email" name="Email[]">
  <br>
  
  <button type="button" id="add-user">Add user</button>
  <button type="submit">Create users</button>
</form>

Server side it will look like this:

Username [ 0 => "user1", 1 => "user2", ... ]
Email [ 0 => "email1", 1 => "email2", ... ]

Which you can easily transform into the format you want if you really need that.

Sign up to request clarification or add additional context in comments.

1 Comment

I hadn't thought about transforming the format afterward. The problem is I am using Laravel validation but I found how to transform the request. I will do this way, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.