0

I have a form with with a simple input field and I have a button that will allow me to add another input field via javascript using the same name(eg: name="list[]"). When I click the 'add' button to enter multiple email addresses it dynamically adds the new input field but the problem I'm having is when I send it to the PHP script the script only returns the first e-mail and not the others. Any ideas what I could be doing wrong?

-javascript below-

function preparePage() {
  var addEmail = document.getElementById("add_email");
  var putEmail = document.getElementById("put_email");

  addEmail.onclick = function() {
    putEmail.innerHTML += '<input type="text" name="names_list[]"><br />';
    };
 }

window.onload =  function() {
  preparePage();
};

-html below-

  <form action="email_names.php" method="post">
    <div id="put_email">
      <input type="text" name="names_list[]"><br />
    </div>

    <div>
      <div id="add_email"> + </div>

      <input id="email_btn" type="submit" name="email_submit" value="E-mail List">
    </div>
  </form>

-php script below-

  if(isset($_POST['email_submit'])) {
    $names_list = $_POST['names_list'];

    echo '<pre>';
    print_r($names_list);
    echo '<pre>';
}

//This returns 
Array
(
  [0] => [email protected]
)
// instead of
Array
(
  [0] => [email protected]
  [1] => [email protected]
  [2] => [email protected]
)

1 Answer 1

2

Typos?

putEmail.innerHTML += '<input type="text" name="name_list[]"   snip....
                                                ^^^^-- singular name: no "s"



  <input type="text" name="names_list[]"><br />
                           ^^^^^---plural names. WITH "s"

Doing a var_dump($_POST) would confirm this.


and now I see the OP's done a ninja-edit and fixed this up, so guess not...

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

2 Comments

You were correct, I did have a typo and now I fixed it in both the OP and my script, but I am still only getting one email returned when I use print_r().
Ok, my dumbass forgot to the refresh the page after I fixed the typo, Thank you Marc.

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.