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>
Related
I need help extending this JavaScript (borrowed from https://www.quirksmode.org/dom/domform.html):
var appCounter = 0;
function anotherApp() {
appCounter = appCounter + 1;
var newAppField = document.getElementById("keyApp").cloneNode(true);
newAppField.id = '';
newAppField.style.display = 'block';
var newApp = newAppField.childNodes;
for (var i = 0; i < newApp.length; i++) {
var theName = newApp[i].name
if (theName) {
newApp[i].name = theName + appCounter;
}
}
var insertApp = document.getElementById('keyApp');
insertApp.parentNode.insertBefore(newAppField, insertApp);
document.getElementById('appCount').value = appCounter
}
This works fine when element in my form is:
<div id="keyApp" style="display:none">
<input type="text" name="application" id="application">
<input type="text" name="usage" id="usage">
<\div>
But when I add div's around the inputs (bootstrap styling reasons) I loose the ability to update the input names:
<div id="keyApp" style="display:none">
<div class="col-md-2">
<input type="text" name="application" id="application">
</div>
<div class="col-md-2">
<input type="text" name="usage" id="usage">
</div>
<\div>
How do I extend the script to modify the input names in these new div's?
Since there is now another layer, you need to get newApp[i].childNodes[0] now in order to get the actual input elements.
newApp now holds a list of the div elements with col-md-2 styling, and you need to get the children inside of these div elements.
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>
I am working on an application in which contains a few DIVs having IDs like a1,a2,a3 etc.
There is option of navigation DIVs by hitting next and previous button which brings one Div on screen at a time. strong text There are two more actions: Add and Remove. Add adds a Div with ID greated than last ID, for instance if last DIV id was a3 then Add brings a4.
The real issue is removing current DIV. If the user is on Div a2 and hits Remove option then it deletes the current Div by using .remove() method of jQuery
Now navigation breaks because it is sequential. It tries to find Div a2 but does not find. What I think that Ids of all remaining DIVs should be renamed. Since there is no a2 so a3 should become a2 and so on. How can I do that? Code doing different tasks is given below:
function removeQuestion()
{
$("#_a"+answerIndex).remove();
if(answerIndex > 1)
{
if ($("#_a"+(++answerIndex)).length > 0)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
else if($("#_a"+(--answerIndex)).length)
{
$("#_a"+answerIndex).appendTo("#answerPanel");
}
totalOptions--;
}
}
function addQuestion()
{
var newId = 0;
totalOptions++;
var d = 1;
newId = totalOptions;
var _elemnew = '_a'+newId;
$("#_a"+d).clone().attr('id', '_a'+(newId) ).appendTo("#answers_cache");
var h = '<input onclick="openNote()" id="_note'+newId+'" type="button" value=" xx" />';
$("#"+_elemnew+" .explain").html(h)
$("#"+_elemnew+" ._baab").attr("id","_baab"+newId);
$("#"+_elemnew+" ._fx").attr("id","_fasal"+newId);
$("#"+_elemnew+" .topic_x").attr("id","_t"+newId);
$("#"+_elemnew+" .topic_x").attr("name","_t"+newId);
$("#"+_elemnew+" .answerbox").attr("id","_ans"+newId);
$("#"+_elemnew+" .block").attr("onclick","openFullScreen('_ans"+newId+"')");
$('.tree').click( function()
{
toggleTree();
}
);
$('.popclose').click( function()
{
unloadPopupBox();
}
);
}
function next()
{
console.log("Next ->");
if(answerIndex < totalOptions)
{
answerIndex++;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
function previous()
{
console.log("Next <-");
if(answerIndex > 1)
{
answerIndex--;
console.log(answerIndex);
setInitialAnswerPanel();
}
}
Html of Composite DIV is given below:
<div class="answers" id="_a1" index="1">
<input placeholder="dd" id="_t1" type="text" name="_t1" class="urduinput topic_masla" value="" />
<img class="tree" onclick="" src="tree.png" border="0" />
<label class="redlabel">
xx :
</label>
<label id="_baab1" class="baabfasal _baab">
</label>
<label class="redlabel">
xx :
</label>
<label id="_fasal1" class="baabfasal _fasal">
</label>
<a title=" ddd" class="block" href="#" onclick="openFullScreen('_ans1')">
<img src="fullscreen.png" border="0" />
</a>
<textarea id="_ans1" class="answerbox" cols="40" rows="15"></textarea>
<span class="explain">
<input onclick="openNote()" id="_note1" type="button" value=" xx" />
</span>
<span style="float:left;padding-top:5%">
plus | <a onclick="removeQuestion()" href="#">minus</a>
</span>
</div>
Why don't you keep currently opened page instead of the index and search for previous and next pages using prev() and next() jQuery tree traversal methods?
Select all div elements containing questions, preferable with a css class selector, use the each method, and assign new ids to them:
$('.questionDiv').each(function(index) { $(this).attr('id', 'a' + (index + 1)); })
That should be enough.
var originalSet = $('.answers');
var container = originalSet.up() ;
var byId = function(a, b){
return $(a).attr('id') > $(b).attr('id') ? 1 : -1;
}
originalSet
.order(byId)
.each(function rearrangeIds(position){
$(this).attr({
'index': poition,
'id': '_a'+position
});
}).appendTo(container)
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.
In my form i am having a button to Add More EmailId where i have to give ten textbox one by one can anybody please tell about appropriate javascript..
Try something like this, its something I ripped from another project.
Wrap your form around the div and when you submit your email addresses will be in an array as the name of the input box is email[].
<div class="cntdelegate">
<div id="readroot" style="display:none;">
<table cellspacing="0">
<tr>
<td><label for="theiremail"><span>Email</span></label><input type="text" name="email[]" id="theiremail" value="Email" class="emailbox" maxlength="100" onFocus="if(this.value=='Email'){this.select()};" onClick="if(this.value=='Email'){this.select()};" /></td>
</tr>
</table>
Remove
<div class="clear"></div>
</div>
<span id="writeroot"></span>
<button style="float:right!important;" type="submit" class="withArrow" name="submit" id="submit" value="submit" alt="Send" title="Send">Book now</button>
<div class="addDelegate" style="float:left!important;">
Add another delegate
</div>
<div class="clear"></div>
</form>
</div>
<script>
var counter = 0;
function init() {
moreFields();
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = function ()
{
if (self.init)
init();
}
</script>
I'm unsure what html you have but I've created a simple jQuery example here http://jsfiddle.net/TsmTg/2/
Here's the code
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
emailAddress.after(emailAddress.clone());
});
});
This will copy your email input and just add a clone after the original. All the email address inputs will have the same name so you will have to handle parsing the data on the server side. You could modify it so each email address input has a different name by using a counter to append a number to the end of each input, like so:
$(function(){
var emailAddress = $("[name=emailAddress]");
$("#addEmailAddress").click(function(){
var newEmail = emailAddress.clone();
newEmail.attr("name", newEmail.attr("name") + ($("[name^=emailAddress]").length + 1));
emailAddress.after(newEmail);
});
});
Are you using Tables to put the textboxes? In that case, cloning rows from the table easily adds a new row with the contents in a table.
Add your HTML code. This will help finding the solution easier.