tim r tim r - 1 month ago 6
PHP Question

JS to add form fields with a button

How I create a do...while loop (or if there is a better way to go about this - please advise) for a form with potentially additional information?

Background - I've got a form that will accept a users assessment of a particular location (such as a basement). Using only 1 location per form, this works nicely and submits to my db without a problem.

Now I want to enhance this form with a "add new location" button. I don't (obviously) want to create new pages but rather a loop that can store the first location, save it (which I know could be done with be a session variable) and then clear the fields for locations 2, 3, 4, etc.

My confusion is around the functionality of the button. What type of button is this? Reset with a unique id such as

new_loc[]
?

And then when I write this as a do...while loop should I do it like this:

<?php
do {
all my form fields
} while (some condition that looks for the button submit);
?>


ok so I have a created a simple JS that can "handle" this.

var counter = 1;
var limit = 5;
function addInput(locInformation){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " locations");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><br><input type='text' name='location[]'>";
document.getElementById(locInformation).appendChild(newdiv);
counter++;
}
}


Now the problem is that JS will add 1 new field - any suggestions on how to add a massive block of HTML to the JS? I tried adding all my fields to the JS and I get a whole bunch of unclosed string errors.

Answer

Ok I've figured this out. Thanks to Marc B for suggesting JS.

HTML for the button

<input style="margin-left:5px;" class="btn btn-primary" type="button" value="Add Additional Location"  onClick="addInput('locInformation');">

JS

var counter = 1;
var limit = 5;
function addInput(locInformation){
         if (counter == limit)  {
          alert("You have reached the limit of adding " + counter + " inputs");
     }
     else {
          var newdiv = document.createElement('div');
          newdiv.innerHTML = "<h3>Location " + (counter + 1) + "</h3>" + document.getElementById('additionalLoc').innerHTML;
          document.getElementById(locInformation).appendChild(newdiv);
          counter++;
     }
}

And then lastly is the new locInformation stuff:

<div id="additionalLoc" language="text">
huge block of HTML with additional fields
</div>
Comments