Livequery and each() - javascript

i have an .each() loop doing something on all matching elements. but i also have a way to add those elements.... i'm trying to get livequery to realize that a new element has been added and run it through the same each loop.
here's a general setup:
http://jsfiddle.net/CUURF/1/
basically, how do i use livequery and each together?
ultimately it is so that i can dynamically add tinymce editor textboxes in metaboxes, but i am fairly certain the problem is that my IDs aren't autoincremting on the add/clone, since the new element isn't in the DOM for the each loop.
edit- i think the biggest thing is that i need the index counter that comes standard w/ .each to work w/ livequery?
edit- here's the code from wpalchemy for looping/cloning
/* <![CDATA[ */
jQuery(function($)
{
$(document).click(function(e)
{
var elem = $(e.target);
if (elem.attr('class') && elem.filter('[class*=dodelete]').length)
{
e.preventDefault();
var p = elem.parents('.postbox'); /*wp*/
var the_name = elem.attr('class').match(/dodelete-([a-zA-Z0-9_-]*)/i);
the_name = (the_name && the_name[1]) ? the_name[1] : null ;
/* todo: expose and allow editing of this message */
if (confirm('This action can not be undone, are you sure?'))
{
if (the_name)
{
$('.wpa_group-'+ the_name, p).not('.tocopy').remove();
}
else
{
elem.parents('.wpa_group').remove();
}
the_name = elem.parents('.wpa_group').attr('class').match(/wpa_group-([a-zA-Z0-9_-]*)/i)[1];
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_delete');
}
}
});
$('[class*=docopy-]').click(function(e)
{
e.preventDefault();
var p = $(this).parents('.postbox'); /*wp*/
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
var the_group = $('.wpa_group-'+ the_name +':first.tocopy', p);
var the_clone = the_group.clone().removeClass('tocopy');
var the_props = ['name', 'id', 'for'];
the_group.find('input, textarea, select, button, label').each(function(i,elem)
{
for (var j = 0; j < the_props.length; j++)
{
var the_prop = $(elem).attr(the_props[j]);
if (the_prop)
{
var the_match = the_prop.match(/\[(\d+)\]/i);
if (the_match)
{
the_prop = the_prop.replace(the_match[0],'['+(+the_match[1]+1)+']');
$(elem).attr(the_props[j], the_prop);
}
}
}
});
if ($(this).hasClass('ontop'))
{
$('.wpa_group-'+ the_name +':first', p).before(the_clone);
}
else
{
the_group.before(the_clone);
}
checkLoopLimit(the_name);
$.wpalchemy.trigger('wpa_copy', [the_clone]);
});
function checkLoopLimit(name)
{
var elem = $('.docopy-' + name);
var the_match = $('.wpa_loop-' + name).attr('class').match(/wpa_loop_limit-([0-9]*)/i);
if (the_match)
{
var the_limit = the_match[1];
if ($('.wpa_group-' + name).not('.wpa_group.tocopy').length >= the_limit)
{
elem.hide();
}
else
{
elem.show();
}
}
}
/* do an initial limit check, show or hide buttons */
$('[class*=docopy-]').each(function()
{
var the_name = $(this).attr('class').match(/docopy-([a-zA-Z0-9_-]*)/i)[1];
checkLoopLimit(the_name);
});
});
/* ]]> */
</script>
and the markup for inside my metabox:
<div id="testimonials">
<h2>Testimonials</h2>
<a style="float:right; margin:0 10px;" href="#" class="dodelete-testimonials button"><span class="icon delete"></span>Remove All</a>
<div id="wpa_loop-testimonials" class="wpa_loop wpa_loop-testimonials"><div class="wpa_group wpa_group-testimonials first">
<span class="icon delete"></span>Remove
<div class="slide_preview">
<div class="preview_wrap">
<img class="preview" src="" alt="preview" />
</div>
<input type="hidden" name="_sidebar_meta[testimonials][0][testimonial_image]" value="" class="img_src" />
<input type="hidden" name="_sidebar_meta[testimonials][0][slide_image_alt]" value="" class="img_alt" />
<button class="upload_image_button button" type="button"><span class="icon upload"></span>Change Photo</button>
</div>
<div class="slide_text">
<label>About Testimonial</label>
<div class="customEditor minimal">
<textarea rows="5" cols="50" name="_sidebar_meta[testimonials][0][testimonial_desc]">I realized it was ME causing all the problems</textarea>
</div>
</div>
</div> <div class="wpa_group wpa_group-testimonials last tocopy">
<h3 class="slide">Testimonial Name:
<input type="text" name="_sidebar_meta[testimonials][1][testimonial_name]" value="" />
</h3>
<span class="icon delete"></span>Remove
<div class="slide_preview">
<div class="preview_wrap">
<img class="preview" src="http://localhost/multi/wp-content/themes/callingintheone/functions/WPAlchemy/images/default_preview.png" alt="_sidebar_meta[testimonials][1][testimonial_image] Preview" />
</div>
<input type="hidden" name="_sidebar_meta[testimonials][1][testimonial_image]" value="" class="img_src" />
<input type="hidden" name="_sidebar_meta[testimonials][1][slide_image_alt]" value="" class="img_alt" />
<button class="upload_image_button button" type="button"><span class="icon upload"></span>Upload Photo</button>
</div>
<div class="slide_text">
<label>About Testimonial</label>
<div class="customEditor minimal">
<textarea rows="5" cols="50" name="_sidebar_meta[testimonials][1][testimonial_desc]"></textarea>
</div>
</div>
</div></div>
<p style="margin-bottom:15px; padding-top:5px;"><span class="icon add"></span>Add Testimonial</p>
</div>
the .tocopy class gets shifted by the alchemy code to a new hidden (by CSS) and last element

Your problem was that each was not executing with the clik. And after that there was nothing to make it run.
fixed code

Answer: http://jsfiddle.net/morrison/CUURF/6/
Notes:
Does not use livequery. There's no need to in this instance.
Keeps track of existing editors in an array. This is faster than cycling through the DOM every time you want an editor. DOM stuff is slow, arrays are fast. This also gives you easy access to any or all of the editors for other things you might do.
Doesn't cycle when a new editor is created. It simply modifies the new editor to have an id of the last one plus 1. This is a huge performance boost.

Related

duplicate and clone div

sorry i do not speak english well, i want to create a tool that allows to duplicate a div thanks to an "input number" and a button and then I also want to clone this tool by reinitializing it to be able to use the tool again , Here is a piece of code:
$(function() {
$('#btn_dupliquate').on('click', function() {
var numDuplication = $('#num-duplication').val();
if (numDuplication > -1) {
var div = $('.common_preview');
$('.result').html('');
for (var i = 0; i < numDuplication; i++) {
$('.result').append(div.clone());
}
}
});
});
$(function() {
$(".heading").keyup(function() {
var heading=$(this).val();
$(".common_preview").html("<div class='bloc'><p class='model'>"+heading+"</p></div>");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toNumDuplicate">
<input type="text" class="heading" />
<br/>
<br/>
<input id="num-duplication" type="number" >
<br/>
<br/>
<button id="btn_dupliquate"> dupliquate </button>
</div>
<div id="toDuplicate">
<div class="common_preview" >
<div class="bloc">
<p class="model">test</p>
</div>
</div>
</div>
<div class="result"></div>
<button id="btn_clone">clone</button>
You could abstract your function to take dynamic selector strings for the duplicate button, duplicate number input, preview div and result div.

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'))),

select id that created dynamically in jquery

I wrote the below jQuery code, in this code when I click on #addbtn 2 text-box with this code below is created
var i = 2;
/* button #add_btn */
$(document).on("click", "#add_btn", function(evt) {
$('.add_checkbox').append("<input type='checkbox' id=foodcheckbox_" + i + " style='margin-bottom:20px;'><br/>");
$(".add_food").append("<input class='wide-control form-control default input-sm foodha' type='text' placeholder='Food' id=food_input" + i + " style='margin-bottom:5px;'>");
$(".add_price").append("<input class='wide-control form-control default input-sm priceha' type='text' placeholder='Price' id='price_input" + i + "' style='margin-bottom:5px;'>");
i++;
});
This code works fine, but when I want to select text-boxes that are added with the above code to get the content of them the selector by id isn't working, below is the code that I use to get value of these text-boxes:
/* button Submit */
$(document).on("click", ".uib_w_60", function(evt) {
var foodid = [];
var priceid = [];
/* your code goes here */
/* first I get id of .foodha class */
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
/* second I get id of .priceha class */
$(".priceha").each(function() {
var pID = $(this).prop("id");
priceid.push(pID);
});
var newfoodpriceid = [];
/* here I dont know why the Id that gotten save
twice in array, for example save with this pattern
[food_input2, food_input3, food_input2, food_input3]
and to prevent this I use a trick and save it in another
array with the code below: */
for (var c = 0; c < priceid.length / 2; c++) {
newfoodpriceid.push({
'foodid': foodid[c],
'priceid': priceid[c]
});
}
/* then I want to get value of text box with exact
id that I select with jQuery selector but the
selector isn't working and the returned value
is nothing but I enter a value in text box that
have below id: */
var pr = $("#" + newfoodpriceid[0].priceid).val();
$("p").text(pr);
});
I explain anything that I think you need to know about what I want to do.
HTML code before I click on addbtn to add text-boxes:
<div class="grid grid-pad urow uib_row_42 row-height-42" data-uib="layout/row" data-ver="0">
<div class="col uib_col_46 col-0_1-12_1-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col center">
<div class="add_checkbox" style="margin-top:5px"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_48 col-0_6-12_6-7" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_food"></div>
<span class="uib_shim"></span>
</div>
</div>
<div class="col uib_col_47 col-0_5-12_5-5" data-uib="layout/col" data-ver="0">
<div class="widget-container content-area vertical-col">
<div class="add_price"></div>
<span class="uib_shim"></span>
</div>
</div>
<span class="uib_shim"></span>
</div>
And that HTML code after click on "add btn" twice
<div class="add_food">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm foodha" type="text" placeholder="Food" id="food_input3" style="margin-bottom:5px;">
</div>
<div class="add_price">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input2" style="margin-bottom:5px;">
<input class="wide-control form-control default input-sm priceha" type="text" placeholder="Price" id="price_input3" style="margin-bottom:5px;">
</div>
As you can see the text-box with the id that I want is generated fine, but I can't select it with using its id.
The only problem I see in your code is that once the page has run you must re-call the "each" function from jquery. When this "loop" is performed there are no "foodha" or "priceha" class cointaining elements. You could put the
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
in a sleep loop or in a js function which you would call later.Like this:
setTimeout(function(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
},1000); //for a second delay
or
function call_after_creating(){
$(".foodha").each(function() {
var IDss = $(this).prop("id");
foodid.push(IDss);
});
}

Create wysihtml5 dynamically

Hi i´m trying to create multiple textareas with wysihtml5 0.3.0.
First generate HTML an then initialize the editors, I must customize blur for each textarea.
<div id="toolbar0" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea0" placeholder="Enter text ..."></textarea>
<br>
<br>
<div id="toolbar1" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea1" placeholder="Enter text ..."></textarea>
<br>
<br>
<div id="toolbar2" style="display: none;">
<a data-wysihtml5-command="bold" title="CTRL+B">bold</a> |
<a data-wysihtml5-command="italic" title="CTRL+I">italic</a>
<a data-wysihtml5-action="change_view">switch to html view</a>
</div>
<textarea id="textarea2" placeholder="Enter text ..."></textarea>
<script>
var editor = [];
var aux = [];
for(var i = 0; i <= 2; i++)
{
editor[i] = new wysihtml5.Editor("textarea" + i, {
toolbar: "toolbar" + i,
parserRules: wysihtml5ParserRules
});
aux[i] = editor[i].getValue();
var log = document.getElementById("log");
editor[i]
.on("blur", function() {
log.innerHTML += "<div>blur"+i+"</div><div>"+ aux[i] +"</div>";
})
}
</script>
Always in the blur event get the last textarea and undefined value:
blur3 undefined,blur3 undefined,blur3 undefined
Could someone help me out, thanks in advance.
You are into a function closure problem. When you define each onblur event, you tell Javascript to read the same i value for all of them (and in the end it becomes i=3).
Change it into this:
editor[i].on("blur", function(index) {
return function() { log.innerHTML += "<div>blur"+index+"</div><div>"+ aux[index] +"</div>"};
}(i));

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