php foreach loop and addmore button in a form - javascript

hello i am using a form to add experience to users where i have a add more button which adds more (clones) the content and users get one more field to add experience
i am using this code to achieve this
<div id="append_palllsjjs"><div class="full_exp_9092k" id='duplicater'>
<div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Company Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="comp[]" required placeholder="company Name" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Department Name <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="dept[]" required placeholder="Department Name" class='cname_990s_EXp'/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
From Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2011" data-initial-month="9" class='TEx_About_allihh' name="exsdate[]" required/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
To Date <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="date" data-initial-day="1" data-initial-year="2012" data-initial-month="10" class='TEx_About_allihh' name="exedate[]" required/>
</div>
</div>
</div><div class="full_one_row_009so">
<div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
Profile <span>*</span>
</div>
<div class="maind_TAxefst67s77s">
<input type="text" name="profile[]" required placeholder="Profile" class='cname_990s_EXp'/>
</div>
</div><div class="obe_left_dibbhsy78">
<div class="header_009sos00dd_d">
</div>
<input type="button" name="addmore" value="Add More" class='button small white' onclick='duplicate();'/>
</div>
</div>
</div></div>
js
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true); // "deep" clone
clone.id = "duplicetor" + ++i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
}
here i want the new fields when added should be empty (right now it is showing the same content with pre filled values in textbox )
second issue is i want to insert the data in table for each value of the array i know this can be donr by foreach loop
PHP
$comps=$_POST['comp'];
$profile=$_POST['profile'];
$exedate=$_POST['exedate'];
$exsdate=$_POST['exsdate'];
$dept=$_POST['dept'];
if(empty($comps) || empty($profile) || empty($exedate) || empty($exsdate) || empty($dept) ){
echo 'Please Fill all the fields marked with *';die;
}
foreach($comps as $value){
// insert into tablename (field1,field2,field3,...) values ('comp1','dep1','profile1'....)
// insert as many feilds as the no of elements in the array
}
please suggest me with this php code how to use the foreach loop so that i can insert as many rows as the no of elements in the array with corrosponging values in another array
pleaes note that this question has two questions written please feel free to help for any of the question.
one is wth php and anothr with ajax

Use following code to clear Cloned form :
NOTE : Must add jquery file in document
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
</script>

Here is code with your new requirement :
To Add remove button if user want to remove form block section user
can easily :
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
var i = 0;
var original = document.getElementById('duplicater');
function duplicate(){
var clone = original.cloneNode(true); // "deep" clone
i = ++i;
clone.id = "duplicetor"+ i; // there can only be one element with an ID
original.parentNode.appendChild(clone);
addButton(clone.id,i);
clearCloneForm(clone.id);
}
function clearCloneForm(id){
var divId = '#'+id;
$(divId).find("input[type^='text'], input[type^='date']").each(function() {
$(this).val('');
});
}
function addButton(id,ii){
var divId = '#'+id;
$(divId).append('<input type="button" value="Remove" class="button small white" id="'+ii+'" onclick="rBlock('+ii+')" />');
}
function rBlock(ii){
$('#'+ii).on('click', function(e){
var parentDiv = $(this).parent();
if(parentDiv.attr('id') !== ii){
parentDiv.remove();
}
});
$('#'+ii).trigger( "click" );
}
</script>

Related

Jquery clone name attribute increase

I'm looking to clone addDriverContent (working fine) and increment the numbers for the name attribute on name="description" to name="description2", name="description3" on the clones
Also if anyone know how to also clone the add button so it works as it should on the clones would be extra points :) Some fiddles would be awesome :)
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="form-control" id="description" name="description" placeholder="Enter the items description"/>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$add_button.click(function(e) {
e.preventDefault();
var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields )
$content.clone().appendTo($clone_wrapper);
});
$clone_wrapper.on("click",".remove_field", function(e){
e.preventDefault();
// this would be more specific.
$(this).parent(".content").remove();
})
});
</script>
As I have no idea what you intend to do with it, I will provide you with my dirty solution for it:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="addDriverContent" style="display:none;">
<div class="content">
<div class="row">
<div class="col-md-12">
<label for="description" class="form-label font-weight-bold">Item Description:</label>
<input type="text" class="description form-control" id="description" name="description" placeholder="Enter the items description"/>
<input type="text" class="fname form-control" id="fname" name="fname"/>
Remove<button type="button" class="add_field_button" id="clone_button">Add another item</button>
</div>
</div>
</div>
</div>
<button type="button" class="add_field_button" id="clone_button">Add another item</button>
<div id="clone_wrapper"></div>
<script type="text/javascript">
$(function($) {
var max_fields = 4;
// origin selector would select all the first div ancestors.
var $content = $("#addDriverContent > .content");
var $clone_wrapper = $("#clone_wrapper") ;
var $add_button = $(".add_field_button"); //Add button ID
$(".add_field_button").click(function() {
//e.preventDefault();
//var counter = 0;
// jquery object is array liked object. Length mean how many elements is selected.
if ( $clone_wrapper.children(".content").length < max_fields ) {
$content.clone().appendTo($clone_wrapper);
//$add_button.clone().appendTo($clone_wrapper);// mine
$(".description").each(function(index) {
$( this ).attr('name', 'description'+index)
});
$(".fname").each(function(index) {
$( this ).attr('name', 'fname'+index)
});
}
});
$(document).on('click', "#clone_wrapper .add_field_button", function () {
$('#addDriverContent + .add_field_button').trigger('click');
})
$(document).on('click', ".remove_field", function () {
//e.preventDefault();
// this would be more specific.
$(this).closest(".content").remove();
});
});
</script>

How to spawn a new div prior to the last div in a container?

I'm trying to create new fields like the first field in this form by clicking on an image, but the fields are spawning below the button to submit and I don't understand why. The behavior I'm looking for is for the new fields to spawn above the button.
Here's my code
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
This is the function:
var element = document.getElementById("add");
element.onclick = function() {
console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.body.appendChild(clone);
}
appendChild, as its name suggests, always appends the new element -- that is, it adds it to the end. What you want is insertBefore:
document.body.insertBefore(clone, ele);
One way to handle this is to wrap your form in a container and append to it :
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').appendChild(clone);
}
<div id="title">
<h1>Monthly Run Operations Assessment</h1>
</div>
<div id="container">
<div class="row">
<div class="col-20" id="row-one">
<label for="name">1. </label>
</div>
<div class="col-60">
<input type="text" id="op" name="op" placeholder="Insert operation here">
</div>
<div class="col-20" id="symbol">
<img src="file:///C:/Users/user/Downloads/plus-circle-solid.svg" id="add">
</div>
</div>
</div>
<div id="submit">
<input type="submit" value="Submit">
</div>
</div>
I combined the above answers to achieve the expected behavior.
var element = document.getElementById("add");
element.onclick = function() {
// console.log("woot");
var ele = document.getElementsByClassName("row")[0];
var clone = ele.cloneNode(true);
var newDiv = document.createElement("div");
document.querySelector('#container').insertBefore(clone, ele);
}

Array of html inputs

I have a html form, where user need to enter the name and address of their office. The number of offices are dynamic.
I want to add an Add More button, so that users can enter the details of any number of offices.
My question is, how can I create an array of inputs where new elements can be added and removed using JavaScript. Currently, I'm doing it using js clone method, but I want an array, so that input data can easily be validated and stored to database using Laravel.
What I'm currently doing..
This is my HTML form where users have to enter the address of their clinic or office. I've taken a hidden input field and increasing the value of that field whenever a new clinic is added, so that I can use loop for storing data.
<div class="inputs">
<label><strong>Address</strong></label>
<input type="text" class="hidden" value="1" id="clinicCount" />
<div id="addresscontainer">
<div id="address">
<div class="row" style="margin-top:15px">
<div class="col-md-6">
<label><strong>Clinic 1</strong></label>
</div>
<div class="col-md-6">
<button id="deleteclinic" type="button" class="close deleteclinic"
onclick="removeClinic(this)">×</button>
</div>
</div>
<textarea name="address1" placeholder="Enter Clinic Address" class="form-control"></textarea>
<label class="text-muted" style="margin-top:10px">Coordinates (Click on map to get coordinates)</label>
<div class="row">
<div class="col-md-6">
<input class="form-control" id="latitude" type="text" name="latitude1" placeholder="Latitude" />
</div>
<div class="col-md-6">
<input class="form-control" id="longitude" type="text" name="longitude1" placeholder="Longitude" />
</div>
</div>
</div>
</div>
</div>
<div class="text-right">
<button class="btn btn-success" id="addclinic">Add More</button>
</div>
And my js code..
function numberClinic(){
//alert('test');
var i=0;
$('#addresscontainer > #address').each(function () {
i++;
$(this).find("strong").html("Clinic " + i);
$(this).find("textarea").attr('name','name'+i);
$(this).find("#latitude").attr('name','latitude'+i);
$(this).find("#longitude").attr('name','longitude'+i);
});
}
$("#addclinic").click(function(e){
e.preventDefault();
$("#addresscontainer").append($("#address").clone());
numberClinic();
$("#addresscontainer").find("div#address:last").find("input[name=latitude]").val('');
$("#addresscontainer").find("div#address:last").find("input[name=longitude]").val('');
$("#clinicCount").val(parseInt($("#clinicCount").val())+1);
});
function removeClinic(address){
if($("#clinicCount").val()>1){
$(address).parent('div').parent('div').parent('div').remove();
$("#clinicCount").val(parseInt($("#clinicCount").val())-1);
}
numberClinic();
}
This way, I think I can store the data to the database but can't validate the data. I'm using the laravel framework.
One way you could do this is by using the position of the input in the parent as the index in the array, then saving the value in the array every time each input is changed. Then you can just add and remove inputs.
Sample code:
var offices = document.getElementById('offices');
var output = document.getElementById('output');
var data = [];
var i = 0;
document.getElementById('add').addEventListener('click', function() {
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('placeholder', 'Office');
var button = document.createElement('button');
var index = i++;
input.addEventListener('keyup', function() {
for (var i = 0; i < offices.children.length; i++) {
var child = offices.children[i];
if (child === input) {
break;
}
}
// i is now the index in the array
data[i] = input.value;
renderText();
});
offices.appendChild(input);
});
document.getElementById('remove').addEventListener('click', function() {
var children = offices.children;
if (children.length === data.length) {
data = data.splice(0, data.length - 1);
}
offices.removeChild(children[children.length - 1]);
renderText();
});
function renderText() {
output.innerHTML = data.join(', ');
}
JSFiddle: https://jsfiddle.net/94sns39b/2/

create textboxes and Insert data at page loading

I would like to know how can I create textboxes and insert data at page load.
What I'm trying to do is open an array string from a database, create the textboxes and populate the textboxes at page load.
I have an array string from an ms sql database that looks something like this
test,test;bla;bla2;test44;test55;test66
I separated each individual array with ; and I would like to create textboxes and insert the values into a textbox, one-by-one, so the end result would look like this:
I don't know how to do it using the code below.
Whatever I try I mess up the add/remove functions or I end up cloning all textboxes when the plus button is clicked.
THANKS
SEE CODE BELOW OR GO TO https://jsfiddle.net/kj3cwww0
<script type='text/javascript'>//<![CDATA[
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('#template_add_form'),
formArray = [ clone($template) ], // init array with first row
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
updateForm(); // first init. of form
});
//]]>
</script>
<script id="template_add_form" type="text/template">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</script>
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
FORM SUBMIT CODE:
<body>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
......the rest of the existing code goes here...
</div>
</form>
</body>
CALLING IT VIA CLASSIC ASP:
if strComp(Request.Form("action"), "submit")= 0 then
Response.write("IT WORKS")
end if
Here is a solution that works :
$(function() {
var clone = function(tmpl) {
return $((tmpl.clone()).html())
},
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),
formArray = [ ], // init array enpty
$formEntries = $('#entries');
$(document).on('click', '.btn-add', function() {
formArray.push(clone($template));
updateForm();
// set focus to adding row = last element in array
$(formArray).last()[0]
.find('input')
.first()
.focus();
});
// remove not working yet
$(document).on('click', '.btn-remove', function(evt) {
var id;
// iterate over formArray to find the currently clicked row
$.each(formArray, function(index, row) {
if ( row.has(evt.currentTarget).length == 1 ) {
id = index; // click target in current row
return false; // exit each loop
}
});
formArray.splice(id, 1);
updateForm();
});
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
var updateForm = function() {
// redraw form --> problem values are cleared!!
var lastIndex = formArray.length - 1,
name; // stores current name of input
$formEntries.empty(); // clear entries from DOM becaue we re-create them
$.each(formArray, function(index, $input) {
// update names of inputs and add index
$.each($input.find('input'), function(inputIndex, input) {
name = $(input).attr('name').replace(/\d+/g, ''); // remove ids
$(input).attr('name', name);
});
if (index < lastIndex) {
// not last element --> change button to minus
$input.find('.btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}
$formEntries.append($input);
});
};
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
$('#template_add_form').remove();
});
.entry:not(:first-of-type)
{
margin-top: 10px;
}
.glyphicon
{
font-size: 12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<form id="loanform" name="loanform" action="test5.asp" role="form" autocomplete="off" method="post">
<INPUT type="hidden" name="action" value="submit">
<div class="container">
<div class="row">
<div class="control-group" id="fields">
<label class="control-label" for="field1">
<h3>Enter your loans below</h3>
</label>
<div class="controls">
<div class="entry input-group col-xs-3">How much extra money can you pay per month?
<input class="form-control" name="extra" type="text" placeholder="Extra/month">
</div>
<br>
<div id="entries"></div>
</div>
<div class="input-group-btn">
<div class="col-xs-5">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<br> <small>Press <span class="glyphicon glyphicon-plus gs"></span> to add another loan</small>
</div>
</div>
</div>
<div id="template_add_form" type="text/template" style="display: none;">
<div class = "entry input-group col-xs-9">
<div class = "col-xs-3">
<input class = "form-control" name="balance" type = "text"
placeholder = "Loan Balance" required = "required"/>
</div>
<div class="col-xs-3">
<input class="form-control" name="rate" type="text" placeholder="Interest Rate" required="required" />
</div>
<div class="col-xs-3">
<input class="form-control" name="payment" type="text" placeholder="Minimum Payment" required="required"/>
</div>
<span class="input-group-btn col-xs-1">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span >
</button>
</span>
</div>
</div>
</form>
</body>
Here's what I changed to your code :
Changed the template which was a <script> to a <div>, and hid it by default using style="display: none;" :
<div id="template_add_form" type="text/template" style="display: none;">
Initialized array empty, so that we can put our own first line : formArray = [ ],
Created a function to add a string in the form :
var addToForm = function (stringValue) {
values = stringValue.split(";");
for (var i = 0; i < values.length; i+=3) {
var newLine = clone($template);
var fields = newLine.find('.form-control');
var toAdd = Math.min(values.length-i, 3);
for (var j = 0; j < toAdd; j++) {
fields[j].value = values[i+j];
}
formArray.push(newLine);
}
}
At the end, I added some example data, then pushed an empty line and updated the form :
addToForm("2;3;4;5;6;7");
formArray.push(clone($template));
updateForm();
EDIT : I also deleted the template div at the end so that it isn't taken into the form when you submit :
$('#template_add_form').remove();
To be able to do that, I cloned it entirely at start :
$template = $('<div>').addClass("entry input-group col-xs-9").append(clone($('#template_add_form'))),

dynamically creating div using javascript/jquery

I have two div called "answerdiv 1" & "answerdiv 2" in html.
now i want to give/create div id uniquely like "answerdiv 3" "answerdiv 4" "answerdiv 5" and so on.
Using javascript/jquery how can i append stuff in these dynamically created divs which id should be unique?
in my project user can add "n" numbers of div, there is no strict limit to it.
Help me out.
Thanks in Adv
================================================================================
My HTML code is:
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
My JS code:
function exchangeLabelsanswertxt(element)
{
var result = $(element).val();
if(result!="")
{
$(element).remove();
$("#answertextdiv").append("<label id='answertext' onClick='exchangeFieldanswertxt(this);'>"+result+"</label>");
}
}
function exchangeFieldanswertxt(element)
{
var result = element.innerHTML;
$(element).remove();
$("#answertextdiv").append("<textarea id='answertext' name='answertext' placeholder='Type answer here' rows='2' cols='40' tabindex='6' onBlur='exchangeLabelsanswertxt(this);'>"+result+"</textarea>");
}
Now from above code I want to append all stuff in unique "answertextdiv" id.
If your divs are in a container like:
<div id="container">
<div id="answerdiv 1"></div>
<div id="answerdiv 2"></div>
</div>
you could do something like:
//Call this whenever you need a new answerdiv added
var $container = $("container");
$container.append('<div id="answerdiv ' + $container.children().length + 1 + '"></div>');
If possible, try not to use global variables...they'll eventually come back to bite you and you don't really need a global variable in this case.
You can try something like this to create divs with unique ids.
HTML
<input type="button" value="Insert Div" onClick="insertDiv()" />
<div class="container">
<div id="answerdiv-1">This is div with id 1</div>
<div id="answerdiv-2">This is div with id 2</div>
</div>
JavaScript
var i=2;
function insertDiv(){
for(i;i<10;i++)
{
var d_id = i+1;
$( "<div id='answerdiv-"+d_id+"'>This is div with id "+d_id+"</div>" ).insertAfter( "#answerdiv-"+i );
}
}
Here is the DEMO
You should keep a "global" variable in Javascript, with the number of divs created, and each time you create divs you will increment that.
Example code:
<script type="text/javascript">
var divCount = 0;
function addDiv(parentElement, numberOfDivs) {
for(var i = 0; i < numberOfDivs; i++) {
var d = document.createElement("div");
d.setAttribute("id", "answerdiv"+divCount);
parentElement.appendChild(d);
divCount++;
}
}
</script>
And please keep in mind that jQuery is not necessary to do a lot of things in Javascript. It is just a library to help you "write less and do more".
I used below JQuery code for the same
$("#qnty1").on("input",function(e)
{
var qnt = $(this).val();
for (var i = 0; i < qnt; i++) {
var html = $('<div class="col-lg-6 p0 aemail1"style="margin-bottom:15px;"><input type="text" onkeyup= anyfun(this) class="" name="email1'+i+'" id="mail'+i+'" > </div><div id=" mail'+i+'" class="lft-pa img'+i+' mail'+i+'" > <img class="" src="img/btn.jpg" alt="Logo" > </div> <div id="emailer1'+i+'" class=" mailid "></div>');
var $html=$(html);
$html.attr('name', 'email'+i);
$('.email1').append($html);
}
}
my HTML contain text box like below.
<input type="text" name="qnty1" id="qnty1" class="" >
and
<div class="email1">
</div>
you need a global counter (more generally: a unique id generator) to produce the ids, either explicitly or implicitly (the latter eg. by selecting the last of the generated divs, identified by a class or their id prefix).
then try
var newdiv = null; // replace by div-generating code
$(newdiv).attr('id', 'answerdiv' + global_counter++);
$("#parent").append(newdiv); // or wherever
var newdivcount=0;
function insertDivs(){
newdivcount=newdivcount+1;
var id="answerdiv-"+(newdivcount);
var div=document.createElement("DIV");
div.setAttribute("ID",id);
var input=document.createElement("TEXTAREA");
div.appendChild(input);
document.getElementById('container').appendChild(input);
}
<button onclick="insertDivs">InsertDivs</button>
<br>
<div id="container">
<div id="answertextdiv">
<textarea id="answertext" name="answertext" placeholder="Type answer here" rows="2" cols="40" tabindex="6" onBlur="exchangeLabelsanswertxt(this);"></textarea>
</div>
</div>
Here is the another way you can try
// you can use dynamic Content
var dynamicContent = "Div NO ";
// no of div you want
var noOfdiv = 20;
for(var i = 1; i<=noOfdiv; i++){
$('.parent').append("<div class='newdiv"+i+"'>"+dynamicContent+i+"</div>" )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent">
</div>

Categories