Adding select boxes dynamically - javascript

I have made a simple dynamic form to generate input boxes.
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+"/>
<input type="button" onclick="removeSelect();" value="-"/>
<input type="button" onclick="xmlData();" value="XML" />
</div>
<div id="main">
</div>
</body>
Here's the javascript code:
(function () {
var selele=0;
var brindex=0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
var textbox = document.createElement('input');
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
});
I can't get it to work on jsFiddle, the buttons don't work.
They work fine if I embed it in a tag.
Can anybody help me fix them.
EDIT: I guess i added anonymously because I wanted the var selele and brindex globally for all these functions.
I have made the code changes.
JSFIDDLE

Your functions are within an anonymous function and thus not available from outside.
First remove the code from the anonymous function (see here: http://jsfiddle.net/uH84W/6/), then fix the console errors you get (I assume that's not the whole code).
function addSelectBox() {...

In your fiddle you select onload but you change onload to no warp-in or no warp-in now it's work fine

Related

Create div Using Array

I have an array of strings, I want to show each array element in its own <div> tag like
<div "class">one</div><div class"two">one</div> and each div tag should have a class that is common for all. All process start on click button
BUTTON CODE
<asp:Button OnClientClick="abc();" runat="server" />
JAVASCRIPT FUNCTION
function abc()
{
debugger;
var arrayVariable = "one,two,three";
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
}
You need to convert string into array first.
Use this:
function abc()
{
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
Use This
<asp:Button OnClientClick=" javascript:return abc();" runat="server" />
<script>
function abc() {
debugger;
var stringVariable = "one,two,three"; // string
var arrayVariable = stringVariable.split(","); // now string to array
var arrayLength = arrayVariable.length;
var temp;
for (i = 0; i < arrayLength; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
$('#inputcomshow').append(temp);
//document.getElementById("#inputcomshow").value = replaced
}
return false;
}
</script>
Try it with less number variable and pure javascript, because you only used single line jQuery code $('#inputcomshow').append(temp);.
function abc(){
var arrayVariable = "one,two,three";
arrayVariable = arrayVariable.split(',');
for (i = 0; i < arrayVariable.length; i++) {
temp = document.createElement('div');
temp.className = 'results';
temp.innerHTML = arrayVariable[i];
document.getElementById("inputcomshow").appendChild(temp);
}
}

Converting if...else statement into for-loop

I have one generous piece of code with several if...else statements and I would need to convert this into a loop. The problem is, each time it makes a loop, there must be some different id to the function so it works properly.
Let's take a look at the code:
// Count how many inputs there are in element with id "tempResult"
var inputCount = document.getElementById('tempResult').getElementsByTagName('input').length;
if (inputCount == 1) // if there is 1 input, generate 1 line
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
}
else if (inputCount == 2) // if there are 2 inputs, generate 2 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
}
else if (inputCount == 3) // if there are 3 inputs, generate 3 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
}
else if (inputCount == 4) // if there are 4 inputs, generate 4 lines
{
var str = document.getElementById('tempString1').value;
var arrayOfStrings1 = str.split('*');
for(var i = 0; i < arrayOfStrings1.length; i++)
{
var div1 = document.getElementById('div1');
var mi1 = document.createElement('input');
mi1.setAttribute('type', 'text');
mi1.setAttribute('size', '5');
mi1.setAttribute('id', 'string1' + (i+1));
mi1.setAttribute('value', arrayOfStrings1[i]);
div1.appendChild(mi1);
}
var str = document.getElementById('tempString2').value;
var arrayOfStrings2 = str.split('*');
for(var i = 0; i < arrayOfStrings2.length; i++)
{
var div2 = document.getElementById('div2');
var mi2 = document.createElement('input');
mi2.setAttribute('type', 'text');
mi2.setAttribute('size', '5');
mi2.setAttribute('id', 'string2' + (i+1));
mi2.setAttribute('value', arrayOfStrings2[i]);
div2.appendChild(mi2);
}
var str = document.getElementById('tempString3').value;
var arrayOfStrings3 = str.split('*');
for(var i = 0; i < arrayOfStrings3.length; i++)
{
var div3 = document.getElementById('div3');
var mi3 = document.createElement('input');
mi3.setAttribute('type', 'text');
mi3.setAttribute('size', '5');
mi3.setAttribute('id', 'string3' + (i+1));
mi3.setAttribute('value', arrayOfStrings3[i]);
div3.appendChild(mi3);
}
var str = document.getElementById('tempString4').value;
var arrayOfStrings4 = str.split('*');
for(var i = 0; i < arrayOfStrings4.length; i++)
{
var div4 = document.getElementById('div4');
var mi4 = document.createElement('input');
mi4.setAttribute('type', 'text');
mi4.setAttribute('size', '5');
mi4.setAttribute('id', 'string4' + (i+1));
mi4.setAttribute('value', arrayOfStrings4[i]);
div4.appendChild(mi4);
}
}
As you can see, we repeat a certain amount of time the same function depending on how much inputs we have in the div tempResult:
var str = document.getElementById('tempStringX').value;
var arrayOfStringsX = str.split('*');
for(var i = 0; i < arrayOfStringsX.length; i++)
{
var divX = document.getElementById('divX');
var miX = document.createElement('input');
miX.setAttribute('type', 'text');
miX.setAttribute('size', '5');
miX.setAttribute('id', 'stringX' + (i+1));
miX.setAttribute('value', arrayOfStringsX[i]);
divX.appendChild(miX);
}
The X, replaced by numbers each time, are important, the function will not properly work without it (except for the divX, I could generate the inputs inside the same div, but whatever). The above code is working perfectly.
What I'm trying to do, is to use a for() instead of if...else(), so that I don't need to manually edit the code each time we add a new div. I'm not very familiar with for() and my tries with the already existing ones in my code as models were not successful.
Here's how the HTML looks like:
<div id="tempResult">
<input type="text" id="tempString1" value="valueTempString1" />
<input type="text" id="tempString2" value="valueTempString2" />
<input type="text" id="tempString3" value="valueTempString3" />
<input type="text" id="tempString4" value="valueTempString4" />
</div>
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
And if you wonder what this whole code is doing, explanation's here. Thanks :)
The if loops in the code you posted would be used as a for loop. i.e, you would be iterating the same times the input count would be. So you can condense the same code into this.
var inputCount = document.getElementById('tempResult')
.getElementsByTagName('input').length;
// First loop that iterates over the input count
for (var j = 1; j <= inputCount; j++) {
var str = document.getElementById('tempString' + j).value,
arrayOfStrings = str.split('*');
// Second loop would iterate over the strings that would be split
for (var i = 0; i < arrayOfStrings.length; i++) {
var div = document.getElementById('div' + j);
var mi = document.createElement('input');
mi.setAttribute('type', 'text');
mi.setAttribute('size', '5');
mi.setAttribute('id', 'string' + j + '-' + (i + 1));
mi.setAttribute('value', arrayOfStrings[i]);
div.appendChild(mi);
}
}
Why do you want the variable to have the number of the item? You could run all code inside the for statement and the variable name doesn't have to change.
thisdiv = document.getElementById('div'+i);
thisdiv....all changes to thisdiv go here

How can I remove unwanted piece of HTML markup on the page?

I have trouble with this piece of code. When I click it once, all is good and the behavior is as designed , but when I click it more than once, then there is all bunch of HTML that appears in the div (text area). How should I revise my JS to make it not happen?
HTML :
<div id="transcriptText">Lorem ipsum dolor sit amet </div>
<br>
<div id="divideTranscript" class="button"> Transform the Transcript! </div>
JS :
window.onload = function() {
var transcriptText = document.getElementById("transcriptText");
var newTranscript = document.createElement("div");
var divideTranscript = document.getElementById("divideTranscript");
divideTranscript.onclick = EventHandler;
function EventHandler() {
changeText();
}
function changeText() {
var sArr = transcriptText.innerHTML.split(" ");
transcriptText.innerHTML = "";
console.log(sArr);
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}
};
Here is it live http://jsfiddle.net/b94DG/1/
The main problem is that you use the innerHTML property instead of the .textContent property each time.
Here is an improved version of changeText() that doesn't matter how many times you run it:
function changeText() {
var sArr = transcriptText.textContent.split(/\s+/g); // changed
transcriptText.innerHTML = "";
var count = 0;
for (var i = 0; i < sArr.length; i++) {
var item = sArr[i];
if (!item) continue; // changed: don't add spans for empty strings
var newSpan = document.createElement("span");
var newText = document.createTextNode(item);
var dotNode = document.createTextNode(" ");
newSpan.id = "word" + i;
var mouseOverFunction = function () {
this.style.backgroundColor = 'yellow';
};
newSpan.onmouseover = mouseOverFunction;
var mouseOutFunction = function () {
this.style.backgroundColor = '';
};
newSpan.onmouseout = mouseOutFunction;
newSpan.appendChild(newText);
newSpan.appendChild(dotNode);
transcriptText.appendChild(newSpan);
count++;
};
}

Submitting from a dynamically generated form

I have made a dynamically generated a form which creates some selects and input boxes.
I need to do a form submit and need all the data from the selects and inputs into individual variables.
The code goes like this:
HTML CODE :
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+" />
<input type="button" onclick="removeSelect();" value="-" />
<input type="button" onclick="xmlData();" value="XML" />
</div>
<form id="autoPopulation_form">
<div id="main"></div>
</form>
JS CODE:
var selele = 0;
var brindex = 0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var textbox = document.createElement('input');
textbox.setAttribute("name", "text" + selele);
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
selectElement.setAttribute("name", "tag" + selele);
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
selectElement1.setAttribute("name", "acctType" + selele);
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
selectElement2.setAttribute("name", "compare" + selele);
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
selectElement3.setAttribute("name", "match_name" + selele);
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
JSFIDDLE FOR THE SAME :
What I basically want to do is I need all the textboxes with name "text1","text2","text3 in different var's (variables).
I have heard about the jQuery .serialize, but would it help my cause and it would be good if anybody can show me the same in my Fiddle.
use FormData() method to serialize your form:
document.getElementByid('autoPopulation_form').onSubmit = function(){
var frmData = new FormData(this);
console.log(frmData);
};
output of it (tested with clicked + one time):
?tag1=Stocks&acctType1=individual&compare1=contains
&match_name1=scrapedaccounttype
&text1=gsdfgsdgfsgsdfgsdf"
Note: You have to have a submit button to submit the form.
Fiddle
Fiddle with method post

How to access elements(inputs, selects) of a dynamic form

I am having a dynamic form which creates fields dynamically by pressing "+" button.
This form is not binded in the document but generated when we click the + button.
I need to access the form values, how do I achieve that.
what should I use form "get" or "post" .
I have tried by using formdata object or jQuery serialize() but with no success or actually I couldn't figure out a way how to use it correctly .
JSFIDDLE LINK :
code:
HTML :
<body>
<div id="main1">
<input type="button" onclick="addSelectBox ()" name="clickme" value="+" />
<input type="button" onclick="removeSelect();" value="-" />
<input type="button" onclick="xmlData();" value="XML" />
</div>
<form id="autoPopulation_form" method='post'>
<div id="main"></div>
<input type="submit" />
</form>
</body>
JS :
var selele = 0;
var brindex = 0;
function addSelectBox() {
selele = selele + 1;
var spantag = document.createElement("span");
spantag.setAttribute("id", selele);
var parentDiv = document.getElementById("main");
var selectElement = document.createElement("select");
var selectElement1 = document.createElement("select");
var selectElement2 = document.createElement("select");
var selectElement3 = document.createElement("select");
var textbox = document.createElement('input');
textbox.setAttribute("name", "text" + selele);
var arr = new Array("Stocks", "MutualFunds");
var arr2 = new Array("individual", "401k", "IRA");
var arr3 = new Array("contains", "equals");
var arr4 = new Array("scrapedaccounttype", "scrapedtransactiontype");
for (var i = 0; i < arr.length; i++) {
var option = new Option(arr[i]);
selectElement.options[selectElement.options.length] = option;
selectElement.setAttribute("name", "tag" + selele);
}
for (var i = 0; i < arr2.length; i++) {
var option = new Option(arr2[i]);
selectElement1.options[selectElement1.options.length] = option;
selectElement1.setAttribute("name", "acctType" + selele);
}
for (var i = 0; i < arr3.length; i++) {
var option = new Option(arr3[i]);
selectElement2.options[selectElement2.options.length] = option;
selectElement2.setAttribute("name", "compare" + selele);
}
for (var i = 0; i < arr4.length; i++) {
var option = new Option(arr4[i]);
selectElement3.options[selectElement3.options.length] = option;
selectElement3.setAttribute("name", "match_name" + selele);
}
spantag.appendChild(selectElement);
spantag.appendChild(selectElement1);
spantag.appendChild(selectElement2);
spantag.appendChild(selectElement3);
spantag.appendChild(textbox);
parentDiv.appendChild(spantag);
linebreak();
};
function removeSelect() {
var parentDiv = document.getElementById("main");
var removetg = document.getElementById(selele);
if (selele != 1) {
parentDiv.removeChild(removetg);
selele = selele - 1;
} else {
parentDiv.removeChild(removetg);
parentDiv.innerHTML = "";
selele = selele - 1;
}
removeBreak();
};
function linebreak() {
brindex = brindex + 1;
var brtag = document.createElement("br");
brtag.setAttribute("id", brindex);
var parentDiv = document.getElementById("main");
parentDiv.appendChild(brtag);
};
function linespace() {
var myElement = document.createElement("span");
myElement.innerHTML = "&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp";
var parentDiv = document.getElementById("main");
parentDiv.appendChild(myElement);
};
function removeBreak() {
var myElement = document.getElementById(brindex);
var parentDiv = document.getElementById("main");
brindex = brindex - 1;
parentDiv.removeChild(myElement);
};
function xmlData() {
xmlDoc = loadXMLDoc("data.xml");
newel = xmlDoc.createElement("edition");
x = xmlDoc.getElementsByTagName("span")[0];
x.appendChild(newel);
};
window.onload = function () {
$( "autoPopulation_form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
};
You are going to find this funny, but your code is fine exept that your selector is wrong when serializing. You forgot the # because you are selecting an ID. Check your updated Fiddle here: http://jsfiddle.net/veritas87/3542N/8/
window.onload = function () {
$( "#autoPopulation_form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
};
I'm going to take a guess here that you are trying to access them from within Javascript.
If that is the case, the easiest way to give the elements a unique id.
var selectElement = document.createElement("select");
selectElement.id = "select_0";
var selectElement1 = document.createElement("select");
selectElement1.id = "select_1";
var selectElement2 = document.createElement("select");
selectElement1.id = "select_2";
var selectElement3 = document.createElement("select");
selectElement1.id = "select_3";
var desiredSelect = document.getElementById("select_3");
You can also give them a name property, in which case you can access them through the form element, or document.getElementsByName. Just be aware the second one will return an array of items, or null.

Categories

Resources