jQuery - set array values to the input with the same name - javascript

I was trying to set the array values to the input field named attachments[]
I have array stored in js variable attachArray
What I have tried is,
$('[name="attachments"]').attr('value', attachArray);
or
$('[name="attachments"]').val(attachArray);
But getting empty attachments in the controller like this,
array(1) { ["attachments"]=> array(1) { [0]=> string(0) "" } }
What I'm doing wrong?
EDIT
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse…
<input type="hidden" name="attachments[]">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>

As far as I understand is that you want to spread the content of an JavaScript array to multiple fields that PHP on the other hand interprets as an array.
I changed the inputs from hidden to text just to make it a little bit more clear and so you can see how the values do look like. Don't forget to undo this in your code.
const attachArray = [
'val1',
'val2',
];
const attachments = $('[name="attachments[]"]');
for ( let i = 0; i < attachments.length; i += 1 ) {
$( attachments[ i ] ).val( attachArray[ i ] );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse… <br>
<input type="text" name="attachments[]"><br>
<input type="text" name="attachments[]">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
But this is a lot of code to do. I think it might be easier to send the array as JSON and use PHPs json_decode to convert it back into an array, like so:
const attachArray = [
'val1',
'val2',
];
$('[name="attachments"]').val( JSON.stringify( attachArray ) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse… <br>
<input type="text" name="attachments">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
And do something like
$attachments = json_decode( $_POST[ 'attachments' ] );

Since it's a hidden input, so
Either:-
$('[name=attachments]').val(attachArray);
OR
$('input:hidden[name=attachments]').val(attachArray);
Will work.
Note:- Use the backslashes(Escape internal brackets with \\(no space)).

you have input field with name as attachments[] so try this
$('[name="attachments[]"]').val(attachArray);

Mention id to a hidden field and you are sending array through the form so declare hidden field name with square brackets like below.
<input type="text" name="attachments[]" id="attachments">
And bind your array with the jquery val() method.
$('#attachments').val(attachArray);
For Future Reference :-)

Related

Multiple widgets for one form field in Django

I have the following form:
class ExcipientForm(ModelForm):
class Meta:
model = Excipient
fields = (
"Excipient_type",
"Excipient_concentration",
)
widgets = {
'Excipient_type': Select(attrs={
'style' : 'width:100%;',
'class' : 'dropdowns',
}),
'Excipient_concentration': TextInput(attrs={
'class': 'slider',
'type': 'number',
'value':"20",
'max':"100",
'step': "0.1",
'id':"excipient_concentration"
}
)
}
ExcipientFormSet = inlineformset_factory(
Parameters,
Excipient,
ExcipientForm,
can_delete=False,
min_num=1,
extra=0
)
This is the template to post to the form:
<form action="" id="form-container" method="POST"> {% csrf_token %} <div class='row'>
<div class='col'>
<label for="id_API_batch_number" class="form-label">API batch number : </label>
</div>
<div class='col'>
{{ parameter_form.API_batch_number }}
</div>
</div>
<hr class="my-4">
<div class='excipient-form'>
{{ excipient_form }}
{{excipient_form.id.auto_id}}
<input type="range" class="slider" name="slidervalue" value='20' max="100" step="0.1" onchange="updateTextInputRange(this.value);">
</div>
<button id="add-form" type="button">Add Excipient</button>
<hr class="my-4">
<label for="num6" class="form-label">Total Concentration: </label>
{{ parameter_form.Total_concentration }}
<br></br>
<input type="submit" id="submit" class="btn btn-primary" value="Submit">
</form>
I'm trying to get the sliders and it's corresponding number field to "sync".
This is the JS I have at the moment.
//Update Textbox value from slider value
function updateTextInputRange(val) {
document.getElementByID('excipient_concentration').value = val; // text input
//checkValueSum();
}
Some of the things I tried:
Finding out the ID for each instance of the slider and number input. This failed as every instance has the same ID.
Tried using multiple widgets in the same form. This failed the html element just took the properties of the final widget properties.
Tried adding another field in the model and using that as a slider in the forms widget. This does not allow me to "sync" the slider and number values without making a call back to the server.
Any ideas on how this can be accomplished?
Django documentation. MultiWidget.
In your Case:
widget = MultiWidget(widgets={'Excipient_type': Select, 'Excipient_concentration': TextInput})
But try to read documentation. More here: https://docs.djangoproject.com/en/4.1/ref/forms/widgets/#multiwidget

How to use HTML template tag with jQuery?

Something strange bug is going on in my code. I want to use HTML template tag with jQuery, because all the rest of my code is jQuery, but I only found JavaScript examples with it. I tried to "translate" from JavaScript to jQuery, this is what I came up with.
$.getJSON( "../Controller/ControllerBookstore.php?show_books=true", function( data ) {
$.each( data, function( index, value ) {
// let clone = document.getElementById('table-template').content.cloneNode(true);
// clone.querySelector('#id').innerText = value.id;
// clone.querySelector('#author').innerText = value.author;
// clone.querySelector('#title').innerText = value.title;
// clone.querySelector('#isbn').innerText = value.isbn;
let clone = $("#table-template").clone(true);
$("#id",clone).text(value.id);
$("#author",clone).text(value.author);
$("#title",clone).text(value.title);
$("#isbn",clone).text(value.isbn);
//$(".container").append(clone);
$("#header").append(clone);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div id="myAlert" class="alert alert-success collapse">
<span id="alert-text"></span>
<a id="alert-close" class="close" href="#" aria-label="Close">×</a>
</div>
<div class="row" id="header">
<div class="col"><h5>ID</h5></div>
<div class="col"><h5>Author</h5></div>
<div class="col"><h5>Title</h5></div>
<div class="col"><h5>ISBN</h5></div>
<div class="col"><h5>Action</h5></div>
</div>
<template id="table-template">
<div class="row">
<div class="col" id="id"></div>
<div class="col" id="author"></div>
<div class="col" id="title"></div>
<div class="col" id="isbn"></div>
<div class="col buttons">
<button class='btn btn-info edit'>Edit</button>
<button class='btn btn-danger delete'>Delete</button>
</div>
</div>
</template>
<div class="row justify-content-center" >
<form action="" class="col-4">
<input id = "id-box" type="hidden" name="id">
<div class="form-group row">
<label class="col-4">Author</label>
<input id = "author-box" type="text" class="form-control col-8" name="author" placeholder="Enter the author of the book">
</div>
<div class="form-group row">
<label class="col-4">Title</label>
<input id = "title-box" type="text" class="form-control col-8" name="title" placeholder="Enter the title of the book">
</div>
<div class="form-group row">
<label class="col-4">ISBN</label>
<input id = "isbn-box" type="text" class="form-control col-8" name="isbn" placeholder="Enter the ISBN of the book">
</div>
<div class="form-group row">
<button id = "submit" type="submit" name="save" class="btn btn-primary col-12">Save</button>
</div>
</form>
</div>
</div>
For some reason the JavaScript code I commented out works, but it only appends "clone" to my ".container" correctly, on the next line below the form. However I want to attach it to my ".header", but it attaches next to the header, not below it. The jQuery code doesn't do anything, it doesn't attach my "clone" anywhere.
I hope I was clear. Could you please help me to find the reason of the bugs?
A few changes are needed:
The id value of the template has a hyphen which must be escaped in the selector. Two backslashes are needed in the string literal; the first is needed to actually get a backslash in the string. The remaining one will be interpreted by the selector.
Clone the row element within the template, not the template itself. However, jQuery will not know of a DOM within the template tag, so you could just take the HTML content instead of cloning, and then turn that into a jQuery object again (which produces the DOM for it).
Insert the clone just before the template
Code:
let clone = $($("#table\\-template").html()); // <--------
$("#id",clone).text(value.id);
$("#author",clone).text(value.author);
$("#title",clone).text(value.title);
$("#isbn",clone).text(value.isbn);
$("#table-template").before(clone); // <------
As others have commented, id attributes should have unique values, so your template content cannot have id properties (since it gets cloned). Use class attributes instead.
jQuery bug
Hello my friend. You are cloning the incorrect element, because your create a clone of template with the id #table-template. Please, make this change to your code:
...
let clone = $("#table-template").html();
...
The other thing, the cloned code appears next to #header and not below it because you are using a .row class. I propose to create a div below the #header, with the id="body" and append the new content inside:
...
// $("#header").append(clone);
-> $("#body").append(clone);
...
Thanks for the example.
But I don't change the id of the "collapse" div.
The rest of the objects are cloned normally.
<template id="facilities_template">
<div class="collapse">
<div class="form-check icon-check">
<input class="form-check-input" type="checkbox">
<label class="form-check-label font-14" id="facilities_name" ></label>
<i class="icon-check-1 far fa-square color-gray-dark font-20"></i>
<i class="icon-check-2 fa fa-check-square font-20 color-green-dark"></i>
</div>
<div class="mb-3"></div>
</div>
</template>
JavaScript:
let cloneFacility = $($('#facilities_template').html());
$('#facilities_name', cloneFacility).text(value.name);
$('#facilities_name', cloneFacility).attr('data-facility-id', value.id);
$('#collapse', cloneFacility).attr('id','collapse'+ value.id)
$('#facilities_template').before(cloneFacility);
$('#faсility_filter').append(cloneFacility);

selecting all class within this in query

well right now I am doing something like this to find all textbox values which has the same class name.
function generalBottom(anchor) {
var sends = $('input[data-name^="noValues"]').map(function(){
$(this).attr('value',$(this).val());
return $(this).val();
}).get();
}
and i call this function on a onclick of submit button like generalBottom(this)
and I have something like as per my requirement
When I click submit button of User I call a general function passing this as a parameter, but the above code gives me the text values of client as well
["perfect", "hyperjack", "julie", "annoying", "junction", "convulated"], which is undesired, I want only ["annoying", "junction", "convulated"] using my anchor params.
How to do this via my this parameter, I thought to traverse through my tags using children(), parent() but I won't be knowing how many fields user have added as its all dynamic, user can add as many values(text boxes).
I tried this
1) $(anchor).find('.rightAbsNo')
2) $(anchor).find('input[data-name^="noValues"]')
3) $(anchor).find('.rightAbsNo').map(function () {
console.log($(this).find('. showNoButton')); })
None of this worked for me.
My html is somewhat like this, code
<div id="attach0" class="leftbottomno">
<div style="overflow: hidden" class="leftbottomAbsolute" id="">
<form>
<span class="absno"><input type="text" required=""
id="absdelete" data-inputclass="leftbottomAbsoluteNo_class"
value="" class="leftbottomabsolutenotest keys" data-value=""
style="margin-bottom:4px; color: #1c1c1c;"> </span>
<a onclick="addAbsoluteValues(this);" style="margin-left: 50px">
<i class="fa fa-plus-circle color-blue-grey-lighter"></i> </a>
</form>
<a onclick="deleteAbsoluteEmpty(this);> </a><br>
<div class="rightAbsNo" id="yesValueattach">
<div class="rightAbsNoValue">
<input type="text" id="nonattach" placeholder="values"
data-name="noValues" data-inputclass="absYes_class" value="annoying"
class="showNoButton showActivity value" data-value="">
<button type="button" onclick="generalBottom(this);">
<i class="glyphicon glyphicon-ok"></i></button>
</div>
</div>
<div class="rightAbsNo" id="yesValueattach">
<div class="rightAbsNoValue" id=""> <input type="text"
data-name="noValues" data-inputclass="absYes_class" subattribute=""
value="" class="showNoButton showActivity value" data-value="">
<button type="button" onclick="generalBottom(this);">
<i class="glyphicon glyphicon-ok"></i></button>
</div>
</div>
<div class="rightAbsNo" id="yesValueattach">
<div class="rightAbsNoValue" id="">
<input type="text" data-name="noValues"
data-inputclass="absYes_class" placeholder="values" subattribute=""
value="junction" class="showNoButton showActivity value"
data-value="" >
<button type="button" style="display: none;"
onclick="generalBottom(this);">
<i class="glyphicon glyphicon-ok"></i>
</button>
</div>
</div>
</div>
</div>
First of all, you need to define a container to the groups with something like :
<div class="container">input groups</div>
<div class="container">input groups</div>
and change <button type='submit'> to <button type='button'> to prevent submitting the form.
Then change your function to this:
function generalBottom(anchor) {
var all_inputs = $(anchor).parent(".container").find("input");
var input = $(anchor).siblings('input').first();
all_inputs.each(function(){
$(this).val(input.val());
});
}
Here's Jsfiddle
first $(anchor).siblings(input) find inputs
then go through each element from first step and return their value
function generalBottom(anchor) {
var input = 'input[data-name^="noValues"]'
var values = $.map($(anchor).siblings(input), (elemnt, index)=>{
return elemnt.value
})
$('#shows').val(values.join())
}
$('button').on('click',function(){
generalBottom(this)
})
hope this helps

How do I use elements with sequential but different names into an array?

I'm not sure if the title is accurate. I am still getting familiar with jQuery/JavaScript so please feel free to correct my grammar/terms.
Problem: I have a form page that I need to read and validate the user supplied data when the user clicks send. The data I am having trouble with is contact data. The form by default lists two contacts. There is a button which allows the user to add one new contact at a time dynamically to the page. So, my code might need to validate tens or hundreds of contacts on this page. I cannot change the code/format of the form. I can only add Javascript/jQuery to validate the data.
Each contact is set up within a repeat wrapper like this:
<div class="ff-sec-repeat-wrapper">
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">LABELS&STUFF</div>
<div class="ff-col-2 ff-field-col">
<input type="textbox"
id="Membership_Application__c.Contact.A_1_.FirstName"
placeholder=""
name="Membership_Application__c.Contact.A_1_.FirstName"
vatt="STRING"
class="ff-input-type ff-type-text"
data-maxlengthmessage="Maximum 40 characters"
maxlength="40"
value=""
data-requiredmessage="required"
data-isupsert="false"
data-ishidden="false"
data-vatt="STRING">
</div>
</div>
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">LAST_NAME_STUFF_SAME_FORMAT_AS ABOVE</div>
<div class="ff-col-2 ff-label-col">...</div>
</div>
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">EMAIL_STUFF_SAME_FORMAT_AS_ABOVE</div>
<div class="ff-col-2 ff-field-col">
<input type="textbox"
id="Membership_Application__c.Contact.A_1_.Email"
placeholder=""
name="Membership_Application__c.Contact.A_1_.Email"
vatt="EMAIL"
class="ff-input-type ff-type-text"
data-maxlengthmessage="Maximum 80 characters"
maxlength="80"
value=""
data-requiredmessage="required"
data-isupsert="false"
data-ishidden="false"
data-vatt="EMAIL">
</div>
</div>
</div>
<div class="ff-sec-repeat-wrapper">
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">LABELS&STUFF</div>
<div class="ff-col-2 ff-field-col">
<input type="textbox"
id="Membership_Application__c.Contact.A_2_.FirstName"
placeholder=""
name="Membership_Application__c.Contact.A_2_.FirstName"
vatt="STRING"
class="ff-input-type ff-type-text"
data-maxlengthmessage="Maximum 40 characters"
maxlength="40"
value=""
data-requiredmessage="required"
data-isupsert="false"
data-ishidden="false"
data-vatt="STRING">
</div>
</div>
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">LAST_NAME_STUFF_SAME_FORMAT_AS ABOVE</div>
<div class="ff-col-2 ff-label-col">...</div>
</div>
<div class="ff-item-row">
<div class="ff-col-1 ff-label-col">EMAIL_STUFF_SAME_FORMAT_AS_ABOVE</div>
<div class="ff-col-2 ff-field-col">
<input type="textbox"
id="Membership_Application__c.Contact.A_2_.Email"
placeholder=""
name="Membership_Application__c.Contact.A_2_.Email"
vatt="EMAIL"
class="ff-input-type ff-type-text"
data-maxlengthmessage="Maximum 80 characters"
maxlength="80"
value=""
data-requiredmessage="required"
data-isupsert="false"
data-ishidden="false"
data-vatt="EMAIL">
</div>
</div>
</div>
Above is the basic setup. Each repeat wrapper contains multiple rows with different contact's data. There are many fields for each contact, such as LastName, EmailAddress, ContactRole, etc. But I suspect that once I understand how to access one, the others will essentially be accessed the same way.
Importantly (I believe): Each new contact id is sequentially iterated with a Alpha_Number_ combination. So, above, the first contact's FirstName id is Application__c.Contact.A_1_.FirstName, while the eigth contact's would be Application__c.Contact.A_8_.FirstName. This number changes for all other contact fields like LastName and EmailAddress.
At a minimum, how can I retrieve all of the contacts' email addresses into an array? This will allow me to do things like check for duplicate email address and match the supplied email addresses to other data I can already retrieve.
So, you're trying to figure out how to validate something like the following, without manually writing validation for "contact 1, contact 2, ..., contact 8", etc?
Using querySelectorAll will be your friend here. We can use it to grab all of your repeat wrappers and add them to an array, and then you can loop through that array to validate.
Here's a simple example. For demonstration purposes, it will kick out the phony name and add the two valid names to an object. Of course, you'll replace this with your own validation and whatever you do from there. I think effectively what you're looking is a way to loop through an indeterminate amount of fields; which
querySelectorAll
and a simple loop:
for( i = START; i <= NUM_OF_ITEMS; i++ ){
Will make simple work of. Check out the following snippet:
// Run this code when #myform is submitted
document.querySelector('#myform').addEventListener("submit", function(e){
e.preventDefault(); // Prevent page load for demo purposes
var object = {},
valid = 0;
// Grab an array of all the repeat-wrapper fields
var fields = document.querySelectorAll('.ff-sec-repeat-wrapper');
// Loop through that array, it will stop when total # of `repeat-wrappers` has been reached
for( i = 1; i <= fields.length; i++ ){
// The "magic" here is the '+ i +', which is replaced with the current iteration number
// Since i will never be greater than fields.length, it will only run as much as long as needed
FirstName = document.getElementById('Membership_Application__c.Contact.A_'+ i +'_.FirstName').value;
LastName = document.getElementById('Membership_Application__c.Contact.A_'+ i +'_.LastName').value;
//Example Fields:
//Email = document.getElementById('Membership_Application__c.Contact.A_'+ i +'_.Email').value;
//SomeField = document.getElementById('Membership_Application__c.Contact.A_'+ i +'_.SomeField').value;
contact = []; // For demo purposes we're making an associative array of valid contacts
// Put your validation here
// Demo validation will only kick out the fake name "Foo Bar"
if( FirstName != 'Foo' ) contact.push( FirstName );
if( LastName != 'Bar' ) contact.push( LastName );
// If contact is valid, add it to our object
if( contact.length > 0 ) object[valid++] = contact;
}
console.log( object ); // Will contain 0:John, 1:Jane - having skipped `Foo` for not meeting out validation
});
<form id="myform">
<div class="ff-sec-repeat-wrapper">
<div class="ff-item-row">
<div class="ff-col-2 ff-field-col">First
<input type="text" id="Membership_Application__c.Contact.A_1_.FirstName" value="John"/>
</div>
<div class="ff-col-2 ff-field-col">Last
<input type="text" id="Membership_Application__c.Contact.A_1_.LastName" value="Doe" />
</div>
</div>
</div>
<div class="ff-sec-repeat-wrapper">
<div class="ff-item-row">
<div class="ff-col-2 ff-field-col">First
<input type="text" id="Membership_Application__c.Contact.A_2_.FirstName" value="Foo" />
</div>
<div class="ff-col-2 ff-field-col">Last
<input type="text" id="Membership_Application__c.Contact.A_2_.LastName" value="Bar" />
</div>
</div>
</div>
<div class="ff-sec-repeat-wrapper">
<div class="ff-item-row">
<div class="ff-col-2 ff-field-col">First
<input type="text" id="Membership_Application__c.Contact.A_3_.FirstName" value="Jane" />
</div>
<div class="ff-col-2 ff-field-col">Last
<input type="text" id="Membership_Application__c.Contact.A_3_.LastName" value="Smith" />
</div>
</div>
</div>
<input type="submit" />
</form>

Add html elements based on number of JSON keys

I am working on a piece of code in which I want to generate span and textarea elements based on the number of JSON key:value pairs.
This is my html:
<div class="modal fade" id="addPropertyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Property</h4>
</div>
<div class="modal-body">
<div class="input-group input-group-lg">
<span class="input-group-addon">Name</span>
<input type="text" id="newProperty" name="newProperty" class="form-control" placeholder="name">
</div>
<br/>
**<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>**
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="savePropertyBtn" name="action" value="Save Property" class="btn btn-primary"/>
<input type="submit" id="updatePropertyBtn" name="action" value="Update Property" class="btn btn-primary"/>
</div>
</div>
</div>
</div>
</div>
The script which loads the newValue is this:
$(".href-select").click(function() {
var propName = $(this).text();
var propVal = $(this).attr('itemprop');
var json = JSON.parse(propVal, 'UTF-8');
var count = 0;
for (i in json) {
console.log(json[i]);
count++;
}
console.log(count);
$("#newProperty").attr('readonly', true);
$("#newProperty").val(propName);
$("#newValue").val(propVal);
$("#savePropertyBtn").hide();
$("#updatePropertyBtn").
});
I have modded the script to get the individual values from the JSON.
My idea is : to increment the count as I read the JSON values and then use this to add count number of span & textarea elements in the html through iteration. Also I want to add the count in the html and hide it so that I can get the count in the request object as well ( I will be creating a map with the number of values ).
Please help me in achieving my idea.
EDIT : This is what is expected if the JSON contains two pairs.
<div class="input-group input-group-lg">
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
<span class="input-group-addon">Value</span>
<textarea id="newValue" name="newValue" class="form-control" placeholder="value" style="resize:vertical;" ></textarea>
</div>
EDIT 2: This is how the dialog box looks right now :
The value textbox contains the JSON. Now I want the textbox to look like this:
Name: [test222]
Host: [DS01ATA]
Port: [ 22 ]
You have to get the div first, then call the append function on it. For example, if you did $(".input-group"), that would give you a list of all html elements with a class of input-group (notice the period before the class name in the selector). Remember, classes aren't guaranteed unique, so my example is only unique if you only use that class once. Once you have the desired element, you can manipulate that element. In this case, you want to add an HTML element to the div.
$(".input-group").append("<span>Sample html string</span>");
References:
Docs for append: http://api.jquery.com/append/
CSS selector "playground" (with documentation): http://codylindley.com/jqueryselectors/
To copy - paste a div using jQuery
function copyDiv(divId) {
var content = $(divId).html();
var newdiv = $('<div>');
newdiv.html(content);
$(divId).after(newdiv);
return newdiv;
}
Calling copyDiv('#mydiv') will create a div with same content below #mydiv.
jQuery .clone() may also be useful here.
For your case, this function can be called inside your loop
for (i in json) {
var newdiv = copyDiv('#form-div-id');
... // add values to new div like 'i' and json[i]
}

Categories