Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
Kajal Avatar asked Sep 24 '13 07:09

Kajal


2 Answers

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.

like image 183
mitchfuku Avatar answered Oct 01 '22 09:10

mitchfuku


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

like image 29
Awais Umar Avatar answered Oct 01 '22 11:10

Awais Umar