jQuery-Add new elements after user specifies the quantity - javascript

User specifies the quantity of new element (div) to be created and clicks on a button to create the number of elements. The Javascript code is working but I want to use jQuery. Help please!
HTML
Quantity of div: <input type="text" id="quantity" name="quantity" value=""><br /><br />
<button id="create" onclick="addFields()>Create</button>
<div id="container">
</div>
Javascript
function addFields() {
var number = document.getElementById("quantity").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i = 0; i < number; i++) {
container.appendChild(document.createTextNode("Div "+(i + 1)));
}
}
How do I do it in jQuery? Thanks very much

Here's one way to let a user specify the number of divs to append to your container div using jQuery:
$('#create').click(function() {
for (var i = 0; i < $('#quantity').val(); i++) {
$('#container').append('<div>Div '+i+'</div>');
}
})
#container > div {
border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Quantity of div: <input type="text" id="quantity" name="quantity" value=""><br /><br />
<button id="create">Create</button>
<div id="container"> </div>
The CSS is there to visualize the new divs. First you create a click handler and bind it to the button. Then when the button is clicked, it takes the value from the input and uses that to create a loop to append divs to your container.

Related

Reusable function to display input text in div

I have a function that displays text in a div as its typed into an input. Right now it simply checks for each ID go get the value and display the text.
I want to make this function reusable so that I can match different inputs with different divs without writing a unique function for each case.
Here is an example that works using a single input and div:
<body>
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
And I want to be able to repeat this for different sets of unique inputs & divs with a reusable function.
<body>
<!-- First set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- Second set -->
<input type='text' name='name' id='inputBox'>
<div id='displayBox'></div>
<!-- etc... -->
<script type="text/javascript">
var displayText = document.getElementById('inputBox');
displayText.onkeyup = function() {
document.getElementById('displayBox').innerHTML = inputBox.value;
}
</script>
</body>
If you wrap each "set" in a container, and swap your ids for classes, you can can add listeners to each input to watch for changes, find the parent container, find the display box and update its text content.
// Get all of the inputs
const displayText = document.querySelectorAll('.inputBox');
// Attach listeners to all of them
displayText.forEach(input => {
input.addEventListener('keyup', handleChange, false);
});
function handleChange() {
// Find the closest div ancestor element (the container)
const parent = this.closest('div');
// Then locate the display box and update the text content
parent.querySelector('.displaybox').textContent = this.value;
}
.container { margin-bottom: 1em; }
.displaybox { margin-top: 0.2em; height: 1.3em; width: 300px; border: 1px solid black; }
<div class="container">
<input type="text" name="name" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="age" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
<div class="container">
<input type="text" name="location" class="inputBox" placeholder="Type here">
<div class="displaybox"></div>
</div>
It seems you would need to get the ID of each input box and each output box?
function showTypedInput(inputID, outputID) {
var inputBox = document.getElementById(inputID);
var outputBox = document.getElementById(outputID);
inputBox.onkeyup = function(){
outputBox.innerHTML = inputBox.value;
};
}
Then you just reuse this?
showTypedInput("myInputBox", "myOutputBox");
You can create this functionality using following:
function listener(target){
return function(e){target.innerHTML = e.target.value};
}
function init(){
var elems = document.querySelectorAll("input[data-keyuptarget]");
for(var elem of elems){
var target = document.getElementById(elem.getAttribute('data-keyuptarget'));
if (target) elem.onkeyup = listener(target);
}
}
init();
In html just use
<input type='text' name='name' data-keyuptarget="displayBox1">
<div id='displayBox1'></div>
<input type='text' name='name' data-keyuptarget="displayBox2">
<div id='displayBox2'></div>
JS Bin : https://jsbin.com/piwiyapohe/edit?html,output

how to show add button in front of field instead at the top of the first field

this is my code but add button is coming of first field but i want that whenever a new input field came the add button shift next to the new input field.
function add(){
var new_chq_no = parseInt($('#total_chq').val())+1;
var new_input="<input type='text' id='new_"+new_chq_no+"'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no)
}
function remove(){
var last_chq_no = $('#total_chq').val();
if(last_chq_no>1){
$('#new_'+last_chq_no).remove();
$('#total_chq').val(last_chq_no-1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
Try This
var new_id = 0;
function add() {
new_id += 1;
var inp_div = document.getElementById("inputs");
var new_inp = document.createElement("input");
new_inp.setAttribute("id", new_id);
inp_div.appendChild(new_inp);
}
function remove() {
if (new_id >= 1) {
document.getElementById(new_id).remove();
new_id -= 1;
}
}
<div id="inputs">
<input type="text">
</div>
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
Try wrapping the button and the input in a div with css attribute display: inline-block

Modify input names in childnodes with JavaScript

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.

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>

Jquery: How to reorder DIVs after removing a single Div?

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)

Categories