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

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.

Related

i cant pass value to summernote using id

This is my java scripte code but i cant pass value to summernote using id i want to pass pree value to the summernote to be edited but nothing is displayed
<script>
$(document).ready(function()
{
var table = document.getElementById('hotel');
var markupStr;
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
//rIndex = this.rowIndex;
document.getElementById("id").value = this.cells[0].innerHTML;
document.getElementById("hotel_name").value = this.cells[1].innerHTML;
document.getElementById("location").value = this.cells[9].innerHTML;
document.getElementById("rate").value = this.cells[2].innerHTML;
document.getElementById("lno").value = this.cells[3].innerHTML;
document.getElementById("uno").value = this.cells[4].innerHTML;
// document.getElementById("sumsummernote7781").value = this.cells[7].innerHTML;
document.getElementById("acce").value = this.cells[5].innerHTML;
//var markupStr = this.cells[7].innerHTML;
//$('#summernote7781').summernote('code', markupStr);
};
}
});
</script>

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

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

Adding select boxes dynamically

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

Javascript - onclick event is not working

So I have this piece of code:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
console.log (id);
var input = document.createElement("INPUT");
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("BUTTON");
var t = document.createTextNode (i);
btn.appendChild(t);
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
}
};
Now when I have created the button with the for loop, it should also have the onclick event attached to it which writes the current value of i into my input form.
Code I have written produces no errors but when the button is clicked, it simply does not do anything. Why is that?
New version:
window.onload = function () {make_buttons ('calc'); }
function make_buttons (id) {
var input = document.createElement("input");
input.type = 'text';
input.id = 'inp';
document.getElementById(id).appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.id = i;
var txt = document.createTextNode (i);
btn.appendChild(txt);
var make_btn = document.getElementById(id).appendChild(btn);
make_btn.onclick = button_pressed (i);
}
};
function button_pressed (id) {
document.getElementById("inp").value += id;
};
Method document.getElementsByTagName() returns a NodeList collection that you should iterate through.
You need to go in loop through retrieved elements and assign the value attribute to each of them.
So that you can change
document.getElementById(id).appendChild(btn).onclick=document.getElementsByTagName("INPUT").value=i;
to something like this:
var id = 'my-form',
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Click me!';
btn.onclick = function() {
var inputs = document.getElementsByTagName('input');
// NodeList to Array if needed:
// var inputsArray = Array.prototype.slice.call(inputs);
for(var i = 0, l = inputs.length; i < l; i++) {
inputs[i].value = i;
}
return false;
};
document.getElementById(id).appendChild(btn);
DEMO #1
Update:
About your second question, yes it won't work in this way since at the time when your onclick event handler is called it's using the last value assigned to i variable. To avoid this you can just use closures.
For example,
HTML:
<form action="" id="my-form">
<input type="text" id="inp" />
</form>
JavaScript:
var btn,
input,
form,
createHandler;
input = document.getElementById('inp');
form = document.getElementById('my-form');
createHandler = function(i) {
return function() {
input.value += i;
};
};
for(var i = 0; i < 5; i++) {
btn = document.createElement('input');
btn.type = 'button';
btn.value = 'Append ' + i;
form.appendChild(btn);
btn.onclick = createHandler(i);
}
DEMO #2
Also you can use just immediately invoked anonymous function to create that closure in the body of your loop:
for(var i = 0; i < 5; i++) {
// ...
btn.onclick = (function(theNumberToAppend) {
return function() {
input.value += theNumberToAppend;
};
})(i);
}
DEMO #3

Categories

Resources