0

I have an empty form that needs to be filled with what I'd like to call mini-forms dynamically based on a condition. For example,this can be a form that asks for the names and locations of restaurants. Now, based on the number of restaurants(let's say 'm'), I'd like to add to the big form 'm' mini-forms that asks for the name and location. How can I use jQuery to create each of these mini-forms, that take in the name and the location of the restaurant and append them each to the big form. The html would look something like this. But I need to create this dynamically based on how many forms the user would need, and if he would need any.

Edit - I have learned that we cannot nest forms. I have renamed the inner 'form' elements to 'div'.

<form>

<div id = 1> 
Name: <input type = "text" name = "name"> 
Location: <input type = "text" name ="location>
</div>

<div id = 2> 
Name: <input type = "text" name = "name"> 
Location: <input type = "text" name ="location>
</div>

... 
</form>
sosale151
  • 360
  • 2
  • 4
  • 19

3 Answers3

1

First you need to look for changes to the input where the user enters the number of restaurants:

$('#noofrestaurants').change(function(){

Then you need to loop through the number inputted and create new inputs each time:

var restaurants = $('#noofrestaurants').val();
for (var i = 0; i < restaurants; i++){
$('#miniformcontainer').append('<input type="text" name="rest_name[]"/><input type="text" name="rest_loc[]"/>');
}
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
ElendilTheTall
  • 1,344
  • 15
  • 23
0

You can't nest forms. If you want to have repeated inputs in a form, give them array-style names:

<div id = 1> 
Name: <input type = "text" name = "name[]"> 
Location: <input type = "text" name ="location[]">
</div>

The back-end should convert these into arrays. For instance, PHP will fill in $_POST['name'] with an array of all the Name inputs.

The jQuery looks like:

divnum++;
$("form").append("<div id='"+divnum+"'>Name: <input type='text' name='name[]'">Location: <input type='text' name='location[]'></div>");
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You could try something like this:

    <script>
    function addMiniForms(n)
    {
        for (i=0; i<n ; i++)
        {
            var $div = $("<div id='" + i + "'></div>");
            var $labelName = $("<label for='name" + i + "'>Name</label>");
            var $inputName = $("<input type='text' id='name" + i +' />");
            var $labelLocation = $("<label for='location" + i + "'>Location</label>");
            var $inputLocation = $("<input type='text' id='location" + i +' />");
            $div.append($labelName);
            $div.append($inputName);
            $div.append($labelLocation);
            $div.append($inputLocation);
            $("#containerid").append($div);
        };
    };
</script>

I have not tested this code, so it might need some tweaking.

Ivo
  • 5
  • 3