So I have dynamic add textbox which is for COLOR, What I want is that if the user input a color then add 2 times for e.g. blue then red then yellow, so if the user submits it. It will go through the database as blue,red,yellow.
Here's the code with javascript function of adding textbox
function addElement() {
var ni = document.getElementById('myDiv');
var numi = document.getElementsByName('theValue');
var num = (numi.length + 1);
var newdiv = document.createElement('div');
var divIdName = 'my' + num + 'Div';
newdiv.setAttribute('id', divIdName);
newdiv.setAttribute('name', 'theValue');
newdiv.innerHTML = '<div class="form-group"><label for="color" class="control-label col-xs-4"><p class="left"></p></label> <div class="col-xs-7"> <input type=text id=' + num + 'value= ' + num + ' class= "req"><a class="btn btn-default bt" href="javascript:remove(' + divIdName + ')">Remove</a>';
ni.appendChild(newdiv);
}
function remove(dId) {
var ni = document.getElementById('myDiv');
ni.removeChild(dId);
}
<label for="color" class="control-label col-xs-4">
<p class="left">Color/s</p>
</label>
<div class="col-lg-1">
<input name="color[]" class="req" id="theValue[]" autocomplete = "off" required/>
<div id="myDiv"></div>
<p><a class="btn btn-default bt " role="button" href="javascript:addElement()" >Add Color</a></p>
<div style='clear: both;'></div>
</div>
</div>
I've tried to keep the code in the same vein as you already have, however, there are other things that you can do to improve this, but those will come in time, namely; using things such as knockout.js and html templates.
Also, I don't know how you are storing the data in the database, so matching the names/Ids of the form controls to what you will load and save from storage is another topic.
Note that when removing items, do not decrement the controlIndex - it is purely for unique identification. If you want finer control of the indexing, then arrays (and maybe knockout.js) may come into it.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<p class="left">
<label for="color" class="control-label col-xs-4">Color/s</label>
</p>
<div class="col-lg-1">
<div id="myDiv">
<input name="color0" class="req" id="color0" autocomplete="off" required />
</div>
<p><a class="btn btn-default bt " role="button" href="javascript:addElement()">Add Color</a>
</p>
<div style='clear: both;'></div>
</div>
<script type="text/javascript">
// Create an index for the control Ids
// First one (and fixed on page) is 0 (color0).
var controlIndex = 0;
// Main Div for additional elements.
var myDiv = document.getElementById("myDiv");
function addElement() {
// Next index.
controlIndex++;
// Create new Div for new elements to be grouped in.
var newDiv = document.createElement("div");
newDiv.id = 'colorDiv' + controlIndex;
// Create new input element and set its properties.
var newElement = document.createElement("input");
newElement.id = newElement.name = 'color' + controlIndex;;
newElement.class = 'req';
newElement.setAttribute('required', 'required');
newElement.setAttribute('autocomplete', 'off');
// Create link to enable removal of new Div.
var newRemovalLink = document.createElement("a");
newRemovalLink.class = 'btn btn-default bt';
newRemovalLink.setAttribute('href', "javascript:remove('" + newDiv.id + "')");
newRemovalLink.innerHTML = ' X ';
// Add the elements to the new Div and add that to the main Div.
newDiv.appendChild(newElement);
newDiv.appendChild(newRemovalLink);
myDiv.appendChild(newDiv);
}
function remove(elementId) {
// Get the main Div.
var myDiv = document.getElementById('myDiv');
// Get the Div (or other element) to remove.
var element = document.getElementById(elementId);
// Remove it from the main Div.
myDiv.removeChild(element);
}
</script>
</body>
</html>
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.
enter image description herethis is simple text boxes i give the value and add them ![enter image description here][2]
when I add more text boxes with append query now the sum is not calculating
[enter image description here][3]
THis is jquery code of iam apending two divs with Two ids and text boxes are also have there ids
Use jquery features for implement complex thing in a very easier way...
It provides Huge Library with number of functions and Flexibility for executing your code in cross browsers
HTML
<div class="row">
<button type="button" class="btn btn-success add-more">ADD MORE</button>
</div>
<div class="form-group" id="ele">
<div class="row" id="item1">
<div class="row">
<input type="number" class="num1">
<label>+</label>
<input type="number" class="num2">
<label>SUM</label>
<input type="number" class="sum" readonly="true">
<button type="button" class="btn btn-success remove">x</button>
</div>
</div>
</div>
JQUERY Script
var item = $('#item1').html();
var cnt = 0;
$('.add-more').click(function() {
cnt++;
$('#ele').append("<div class='row' id='item" + cnt + "'>" + item + "</div>");
});
$(document).on('click', '.remove', function() {
$(this).closest('.row').remove();
});
$(document).on('keyup', '.num1,.num2', function() {
if ($(this).hasClass('num1')) {
var num1 = parseInt($(this).val());
var num2 = parseInt($(this).siblings('.num2').val());
$(this).siblings('.sum').val(num1 + num2);
} else if ($(this).hasClass('num2')) {
var num2 = parseInt($(this).val());
var num1 = parseInt($(this).siblings('.num1').val());
$(this).siblings('.sum').val(num1 + num2);
}
});
Check Demo Here
I have a form where I need such facility where user input some data in textfield and hits enter that time using jquery it should create new controls like new textfield, dropdown menu, textfield. and it works also, but it has a bug like when user input another data and hits enter that time value of previous controls, dropdown and textfield changes to its default.
Here is my code:
<script type="text/javascript">
function addMbo(value){
var div = document.getElementById('mboTable');
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
event.preventDefault();
var divName = document.getElementById('mboName');
var divState = document.getElementById('mboState');
var divProgress = document.getElementById('mboProgress');
divName.innerHTML = divName.innerHTML + "<input class=form-control type=text name=mboName value='" + value + "' id=mboNamw/>"
divState.innerHTML = divState.innerHTML + "<select class=form-control > <option value=1>In Progress </option><option <value=2>Completed</option><option value=3>Cancled</option></select>"
divProgress.innerHTML = divProgress.innerHTML + "<input class=form-control type=text name=progress id=progress />"
document.getElementById('mboNameInput').value = null;
}
}
</script>
HTML code:
<div class="col-sm-4">
<div class="row">
<div class="col-sm-5">
<b>Objectives</b>
</div>
<div class="col-sm-4">
<b>Status</b>
</div>
<div class="col-sm-3">
<b>Compl. %</b>
</div>
</div>
<div class="row">
<div id="mboTable">
<div id="mboName" class="col-sm-5"></div>
<div id="mboState" class="col-sm-4"></div>
<div id="mboProgress" class="col-sm-3"></div>
</div>
</div>
<div class="row" >
<div class="col-sm-5">
<input type="text" id="mboNameInput" class="form-control " onkeydown="addMbo(this.value)" placeholder="Your MBO...">
</div>
</div>
</div>
here is jsfiddle
When you do innerHTML on any element, it will completely destroy what ever content already there inside the elment.
Rather you should appndChild as shown below,
var divName = document.getElementById('mboName');
var mboName = document.createElement("INPUT");
mboName.setAttribute("type", "text");
mboName.setAttribute("class", "form-control");
divName.appendChild(mboName );
you can do the related changes to above code and make your things work.
See below code to add select dropdown.
var divState = document.getElementById('mboState');
var selectData = [{name:"In Progress",value:"1"},{name:"Completed",value:"2"},{name:"Cancelled",value:"3"}];
var selectList = document.createElement("select");
selectList.class = "form-control";
divState.appendChild(selectList);
for (var i = 0; i < selectData.length; i++) {
var option = document.createElement("option");
option.value = selectData[i].value;
option.text = selectData[i].name;
selectList.appendChild(option);
}
I'm trying to add a menu page to my wordpress site for series script.
To easy understand "bolum" means episode and "sezon" means season.
Javascript
function addSeason() {
var main_div = document.getElementById("taxonamy-category");
var helper_son = document.getElementById("sezon-son");
var helper_active = document.getElementById("sezon-active");
var last_active = document.getElementById("sezon-" + helper_active.getAttribute("value"));
var ul = document.getElementById("sezon-tabs");
var yeni_sezon = parseInt(helper_son.getAttribute("value"), 10) + 1;
var li = document.createElement("li");
var a = document.createElement("a");
var last_div = document.getElementById("bolumler-" + yeni_sezon - 1);
var div = document.createElement("div");
var a2 = document.createElement("a");
a2.appendChild(document.createTextNode(" + Yeni Bölüm Ekle"));
a2.setAttribute("id", "bolum-add");
a2.setAttribute("onclick", "return addBolum();");
a2.setAttribute("class", "taxonamy-add-new");
div.setAttribute("id", "bolumler-" + yeni_sezon);
div.setAttribute("class", "tabs-panel");
div.setAttribute("style", "display:block;");
last_div.setAttribute("style", "display:none;");
div.appendChild(a2);
main_div.appendChild(div);
a.appendChild(document.createTextNode("Sezon " + yeni_sezon));
a.setAttribute("href", "#sezon-" + yeni_sezon);
a.setAttribute("id", "sezon");
a.setAttribute("onclick", "return focusSeason();");
li.setAttribute("id", "sezon-" + yeni_sezon);
li.setAttribute("class", "tabs");
li.appendChild(a);
ul.appendChild(li);
last_active.removeAttribute("class");
helper_active.setAttribute("value", yeni_sezon);
helper_son.setAttribute("value", yeni_sezon);
}
HTML
<div id="bolumler" class="postbox">
<h2 class="hndle ui-sortable-handle"><span>Bölümler</span></h2>
<div class="inside">
<div id="taxonamy-category" class="categorydiv">
<ul id="sezon-tabs" class="category-tabs">
<li class="tabs" id="sezon-1">
<a id="sezon" onclick="return focusSeason();" href="#sezon-1">Sezon 1</a>
</li>
</ul>
<div id="bolumler-1" class="tabs-panel" style="display:block;">
<a id="bolum-add" class="taxonamy-add-new" onclick="return addBolum();"> + Yeni Bölüm Ekle</a>
</div>
<div id="category-adder">
<input type="button" name="add-sez" id="add-sez" class="button button-primary button-large" value="Sezon Ekle" onclick="addSeason()" />
</div>
</div>
</div>
</div>
and these 2 hidden elements on my html for storing last season etc.
<input type="hidden" name="sezon-son" id="sezon-son" value="1" />
<input type="hidden" name="sezon-active" id="sezon-active" value="1" />
This js function has no effect i'm checking it with chrome.Has anyone know the problem ?
Thanks so much
First of all, you have id dublicate:
<li id=sezon-active> and <input id=sezon-active>
Also, "bolumler-"+yeni_sezon-1 equals NaN, it should be "bolumler-"+(yeni_sezon-1).
You should rename <a id="sezon" ... to <a id="sezon-1" also to make your code work without errors.
Some more fixes made, here is working code:
https://jsfiddle.net/maxim_mazurok/4fj15hav/
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>