0

I've seen a few questions that were similar but not specific enough. This one - Submit form input fields added with javascript - is the closest comparison, but it is overwhelming for me (not really a javascript guy).

I'm trying to have dynamically added inputs which post independently on the next page via PHP. My code is as follows (which I found off google).

FORM PAGE

<script language="javascript">
fields = 0;
function addInput() {
if (fields != 19) {
document.getElementById('text').innerHTML += "<li>Link Title:<br /><input type='text' name='title' /><br />Link Address:<br /><input type='text' name='name' /><br />Description:<br /><input type='text' name='copy' /></li>";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 20 data entries allowed.";
document.form.add.disabled=true;
}
}
</script>

<form name="form" action="form.php" method="post">
<ul class="form">
<li>
Link Title:<br /><input type="text" name="title" /><br />
Link Address:<br /><input type="text" name="name" /><br />
Description:<br /><input type="text" name="copy" />
</li>
<div id="text">

</div>
</ul>
<input type="button" onclick="addInput()" name="add" value="Add input field" /> <input type="submit" value="Submit" />
</form>

POST PAGE - Wasn't sure where to begin since all of the fields are using the name 'title'? - I'll be okay with this page though.

<?php

    echo $_POST['title'];

?>
1
  • try to name them like array, for example name="title[]" and then in php just try to print the data out, like print_r($_POST['title']), you will see the effect /edit you can also put the variable fields into the input name, but it will be harder to handle them after submitting Commented Mar 9, 2012 at 19:09

1 Answer 1

1
innerHTML += "<li>Link Title:<br /><input type='text' name='title' /><

If you change that last bit to

name='title" + fields + "' /><

(watch where the second apostrophe went) then they gain unique names of title0, title1, title2...

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

2 Comments

Looks like it doesn't work. When I try to echo the titles, they print the first input but have errors on the others "Notice: Undefined index: title2"
EDIT - Nevermind this does work, I just added it to the first input (not part of the javascript).

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.