createElement (input) with Id ;with counter ,Id1,Id2,Id3 - javascript

i trie to generate dynamic Input fields with unique Ids but i stucked:
function addTxtBx(){
var txtBxHolder = document.getElementById('txtBoxHolder');
var newTxtBx = document.createElement('input');
newTxtBx.type = 'text';
var i=1;
//newTxtBx.id = document.getElementById("txtWaypoint"[i])
if(i<10){
newTxtBx.id = "txtWaypoint"+[i];
i++;
break;
}
txtBoxHolder.appendChild(newTxtBx);
}
i tried it with a for() but always got Id='name'9,
i know im an trainee. :)

I think so where you miss to loop it properly.
function addTextBox(ops) {
var no = document.getElementById('id1').value;
for (var i = 0; i < Number(no); i++) {
var text = document.createElement('input');
text.type = "text";
text.id = "txtWaypoint" + i; //id created dynamically
document.getElementById('divsection').appendChild(text);
}
}
Try it

Related

How to use for loop to sum a numbers inserted by the user?

i'm trying to create a simple project where the user is prompted to enter how many numbers he would like to add(sum). then when he click the button, a javascript will create a number of input tags equal to the number he inserted and then he will fill them with a number and click another button to calculate the result of the summation and here is the problem. below is a simplified snippet explain what is the problem:
function CL(){
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type","text");
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
}
function Add(){
const y = 0;
const sum = 0;
var is;
for (var i = 1; i < 3; i++) {
is = i.toString();
y = Number(document.getElementById('y'+ is).value);
sum = sum + y;
}
document.getElementById("demo").innerHTML = sum;
}
in the for loop how can i use getElementById with variables id like item1,item2,item3,...,itemN??
is there other way to achieve what i want?
You can take all items with ID "y" + consecutive number prefix on this way document.getElementById('y' + i).value;
Do not use "Add" for function name and Functions do not have to start with capital letters!
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var res = 0;
for (var i = 1; i < 3; i++) {
res = res + +document.getElementById('y' + i).value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
A better way is ...
When you create elements, you can assign them a CLASS attribute that is one for all input elements. You can then take the values from all elements with this class.
Example:
calckStart();
function calckStart() {
const items = document.getElementById("items");
for (var i = 1; i < 3; i++) {
const inpt = document.createElement("input");
inpt.setAttribute("type", "text");
inpt.setAttribute("style", "margin:5px;");
// inpt.setAttribute("id", "y" + i);
inpt.setAttribute("value", "");
inpt.setAttribute("class", "numbers"); //<-- Set class
const newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline);
}
var button = document.createElement('button');
button.innerHTML = 'ClickMe'
items.appendChild(button);
button.addEventListener('click', calculateVal);
}
function calculateVal() {
var list = document.getElementsByClassName('numbers'); //<-- Get by class
var res = 0;
for (var i = 0; i < list.length; i++) {
res = res + +list[i].value;
}
var items = document.getElementById("items");
var result = document.createElement('div');
result.innerHTML = res;
items.appendChild(result);
}
<div id="items"></div>
You can use ...args to collect arguments and use .reduce to add the arguments together.
const items = document.getElementById("items");
for (var i = 0; i < 3; i++) {
var inpt = document.createElement("input");
inpt.setAttribute("type","number"); //replaced with number
inpt.setAttribute("style","margin:5px;");
inpt.setAttribute("id","y"+i);
inpt.setAttribute("value","");
var newline = document.createElement("br");
items.appendChild(inpt);
items.appendChild(newline); //added newline appending
}
function sum(...args) {
return args.reduce((a, b) => a+b); //reduce arguments
}
<div id="items"></div><br /><button onclick="document.getElementById('answer').textContent = 'answer: ' + sum(+y0.value, +y1.value, +y2.value)">Add</button><div id="answer"></div>

add quantity field for every product in the product grid view (ecwid ecommerce)

i keep on trying to manipulate my codes i put something that will define the variable but still not working and having a hard time with the error "Cannot read property '0' of undefined"
Here's my code:
Ecwid.OnPageLoad.add(function(page) {
var x = "ecwid-BuyNow";
for (i = 0; i < x.length; i++) {
var container = document.getElementsByClassName("x")[0];
var t = document.createTextNode("\n\n");
container[i].appendChild(t);
var input = document.createElement('input');
input.type = "number";
input.placeholder = "Quantity";
input.min = "1";
input.name = "qtyAdd";
container[i].appendChild(input);
}
});
Assuming that you placed your javascript code after HTML code, your loop is invalid. You iterate over length of string x, not over elements with class ecwid-BuyNow. And you don't event call variable x, but you search for elements with class x.
BuyNowEcwid.OnPageLoad.add(function(page) {
var x = "ecwid-BuyNow";
var elements = document.getElementsByClassName(x);
for (var i = 0; i < elements.length; i++) {
var container = elements[i];
var t = document.createTextNode("\n\n");
container.appendChild(t);
var input = document.createElement('input');
input.type = "number";
input.placeholder = "Quantity";
input.min = "1";
input.name = "qtyAdd";
container.appendChild(input);
}
});

by clicking on input box twice it's printing it's own html code inside input box

I am creating a dynamic table and getting td values from array, my goal was when I click on any cell that convert to input box and get this td value as input value so we can change and when I click on another td the previous td turn back to it's original position with new or same old value.
Now this is almost happening, problem is when I click on td it turn to input box and when I click again on the same input box it prints it's html code inside the text box as it's value and then the all td's go crazy, like this: <input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'> it creates two input boxes in same time and sometime prints the html code inside td without creating input box. I am new to these things trying to learn and stuck on this for two days.
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 1;
var getInputLength = getInput.length+1;
for(var j=0; j<allTds.length;j++){
allTds[j].onclick = function(){
thisInHtml = this.innerHTML;
var thisId = this.id;
if(inputs.length != 0){
inputsParent.removeChild(inputs);
inputsParent.innerHTML = getInputVal;
flag = 1;
}
this.innerHTML = thisInHtml;
if(getInputVal != ""){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
getInput = document.getElementsByTagName("input");
getInputVal = document.getElementById("thisInputId").value;
}
if(getInputLength > 0){
for(var k =0; k<getInputLength;k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
}
}
}
}
}
http://jsfiddle.net/mohsinali/npckf9xs/6/
After some struggle I came up with the solution on my own and I fix the issue, I also figure it out that it's always simple we just have to think right. It can be more optimize I believe.
var getInput = ""; var inputsParent = ""; var inputs = ""; var thisInHtml = ""; var getInputVal = "";
var thisTdInnerHtml = ""; var input = ""; var flag = 0; var thisInputVal = ""; var thisTdId = "";
var cellIndex = ""; var thisRowIndex = "";
for(var j=0; j<allTds.length;j++){
allTds[j].ondblclick = function(){
thisInHtml = this.innerHTML;
getInput = document.getElementsByTagName("input");
if(getInput.length === 0){
input = this.innerHTML = "<input id='thisInputId' type='text' value='"+thisInHtml+"' style='width: 100px;'>";
thisTdId = this.id;
cellIndex = this.cellIndex;
var rows = document.getElementsByTagName('tr');
for(var o=0; o<rows.length;o++){
rows[o].ondblclick = function(){
thisRowIndex = this.rowIndex-1;
}
}
}
else if(getInput.length > 0){
for(var k=0; k<getInput.length; k++){
inputsParent = getInput[k].parentNode;
inputs = inputsParent.childNodes[0];
thisInputVal = inputs.value;
inputsParent.removeChild(inputs);
flag = 1;
}
}
if(flag === 1){
var getTdById = document.getElementById(thisTdId);
getTdById.innerHTML = thisInputVal;
if(cellIndex === 0){
proArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 1){
proColorArr[thisRowIndex] = thisInputVal;
}
else if (cellIndex === 2){
proPriceArr[thisRowIndex] = thisInputVal;
}
flag = 0;
}
}
}
}

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

Javascript - accessing array in an array

So I have this code:
function make_buttons (id) {
var operators = [["*","multiply"],["/","divide"],["+","add"],["-","divide"],["=","calc_it"]]
var parent = document.getElementById(id);
var input = document.createElement("input");
input.type = 'text'; input.id = 'inp';
parent.appendChild(input);
for (var i = 0;i < 10; i++){
var btn = document.createElement ("button");
btn.innerHTML = i;
btn.id = i;
parent.appendChild(btn);
(function(index) {btn.onclick = function() {input.value += index;}})(i);
}
for (var j = 0; j < operators.length; j++) {
var operators[j][1] = document.createElement ("button");
};
So I have an array wich has array inside of it. Now I want to set the name of the variable to be operator name inside of the array. In current case it should be 'multiply'.
But it gives me a syntax error when doing this.
What I want to achieve is this :
var multiply = document.createElement ("button");
multiply.innerHTML = "*";
multiply.id = "*";
parent.appendChild(multiply);
multiply.onclick = function () {input.value += '*';};
var divide = document.createElement ("button");
divide.innerHTML = "/";
divide.id = "/";
parent.appendChild(divide);
var add = document.createElement ("button");
add.innerHTML = "+";
add.id = "+";
parent.appendChild(add);
var substract = document.createElement ("button");
substract.innerHTML = "-";
substract.id = "-";
parent.appendChild(substract);
But with the array, so that there is less code written and also less repetitiveness.

Categories

Resources