Appending created elements to different divs in Javascript - javascript

I have the following code:
JS :
i.addEventListener("click", function () {
var br1 = document.createElement("br");
var div1 = document.createElement("div");
div1.className = "input-group";
var ipt1 = document.createElement("input");
ipt1.type = "text";
ipt1.className = "form-control";
var span = document.createElement("span");
span.className = "input-group-addon";
var ipt2 = document.createElement("input");
ipt2.type = "text";
ipt2.className = "form-control";
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br1);
});
document.getElementById('modal2body').appendChild(divdiv);
However, when there are multiple <i>s, the divdiv is appended to the last one.
This is all in a for loop, which adds an <i> for each element in a list.
The list might look like ['customers','employees','managers','night-shifts']
There needs to be an option to add the input-group to each one of these. (the i is a FontAwesome 'plus' icon).
The problem I have, is that clicking any of the icons, it will add the input-group to the night-shift list.
I thought I might need to use dynamic variables to fix this.
If it happens that this is the most effective solution, how can I achieve this?
Or is there a better way to do this ?
Screenshot :
In this screenshot, I clicked the + to the right of Customers
This code creates the original 4 input-groups (1 for each section) :
var divdiv = document.createElement('div');
divdiv.id = 'd' + d;
var div1 = document.createElement('div')
div1.className = 'input-group';
var ipt1 = document.createElement('input');
ipt1.type = 'text';
ipt1.className = 'form-control'
var span = document.createElement('span');
span.className = 'input-group-addon';
var ipt2 = document.createElement('input');
ipt2.type = 'text';
ipt2.className = 'form-control'
var div2 = document.createElement('div');
var t = document.createElement('t');
t.className = 'helv-b grey'
t.style.fontSize = '15px';
t.textContent = inputstext[d];
div2.appendChild(t);
var i = document.createElement('i');
i.className = 'fa fa-plus';
i.style.float = 'right'
i.style.fontSize = '20px';
i.style.marginTop= '5px'
i.onmouseenter = i.style.opacity = "60%";
i.onmouseleave = i.style.opacity = "100%";
div2.appendChild(i);
var br1 = document.createElement('br');
var br2 = document.createElement('br');
divdiv.appendChild(div2);
divdiv.appendChild(br1);
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br2);
divdiv.id = 'f' + d;
(inputstext = ['Customers','Employees','Managers','Night-Shifts'])
HTML :
<div class="modal-body" id="modal2body">
</div>
###Update
Screenshots :
I can't figure out how to fix these alignment issues and make them look like my original screenshot.
Also, how do I have 1 input-group already displayed for each section ?

The problem is that the code which adds is event-driven, which means that it will run when the user clicks the add icon. So when the add icon is click the value of divdiv will be the last element of array "Night-Shifts".
Here is a way of doing it using arrays.
var inputstext = ['customers', 'employees', 'managers', 'night-shifts']
var divdivArray = [];
var mainDiv = document.getElementById("modal2body");
for (var d = 0; d < inputstext.length; d++) {
var divdiv = document.createElement('div');
divdiv.id = 'd' + d;
var div1 = document.createElement('div')
div1.className = 'input-group';
var ipt1 = document.createElement('input');
ipt1.type = 'text';
ipt1.className = 'form-control'
var span = document.createElement('span');
span.className = 'input-group-addon';
var ipt2 = document.createElement('input');
ipt2.type = 'text';
ipt2.className = 'form-control'
var div2 = document.createElement('div');
var t = document.createElement('t');
t.className = 'helv-b grey'
t.style.fontSize = '15px';
t.textContent = inputstext[d];
div2.appendChild(t);
var i = document.createElement('i');
i.className = 'fa fa-plus';
i.style.float = 'right'
i.style.fontSize = '20px';
i.style.marginTop = '5px'
i.onmouseenter = i.style.opacity = "60%";
i.onmouseleave = i.style.opacity = "100%";
i.setAttribute("index", d)
div2.appendChild(i);
var br1 = document.createElement('br');
var br2 = document.createElement('br');
divdiv.appendChild(div2);
divdiv.appendChild(br1);
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
divdiv.appendChild(div1);
divdiv.appendChild(br2);
divdiv.id = 'f' + d;
mainDiv.appendChild(divdiv)
divdivArray.push(divdiv);
i.addEventListener("click", function() {
var br1 = document.createElement("br");
var div1 = document.createElement("div");
div1.className = "input-group";
var ipt1 = document.createElement("input");
ipt1.type = "text";
ipt1.className = "form-control";
var span = document.createElement("span");
span.className = "input-group-addon";
var ipt2 = document.createElement("input");
ipt2.type = "text";
ipt2.className = "form-control";
div1.appendChild(ipt1);
div1.appendChild(span);
div1.appendChild(ipt2);
var index = this.getAttribute("index");
divdivArray[index].appendChild(div1);
divdivArray[index].appendChild(br1);
});
}
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class="modal-body" id="modal2body" style="display: inline-block;">
</div>
<html>
Here I save every divdiv inside the array. And also add an index attribute to the <i> element so when it is clicked you can know which divdiv you want to edit.

Related

JavaScript Table content Add and Delete

I'm working on a table content with JS. What I can update with a button or clear data from the table.
Phone Number: phoneNumber.value
Bay Number: bayNumber.Value (it's not added yet, but will work same)
The First column in the table is always the same (Phone Number and Bay Number), but the second column should change what is in the input after I press the save button (it works fine) Just if I press the delete, it deletes the all table.
I think the problem is how I created the table, but don't know how should I fix it.
//FORM//
var form = document.createElement('div');
form.style.width = "500px";
form.style.height = "500px";
form.style.margin = "auto";
form.style.textAlign = "center";
form.style.paddingTop = "20px";
form.style.background = "grey";
form.classList.add("printVisible");
document.body.appendChild(form);
var phoneNumber = document.createElement("INPUT");
phoneNumber.setAttribute("type", "text");
phoneNumber.value = "07";
phoneNumber.classList.add("hiddenPrint");
form.appendChild(phoneNumber);
var bayNumber = document.createElement("INPUT");
bayNumber.setAttribute("type", "text");
bayNumber.value = "Bay Number";
bayNumber.classList.add("hiddenPrint");
form.appendChild(bayNumber);
var buttonSave = document.createElement("BUTTON");
buttonSave.addEventListener("click", saveDatas);
var buttonSaveT = document.createTextNode("Save");
buttonSave.appendChild(buttonSaveT);
form.appendChild(buttonSave);
var buttonClear = document.createElement("BUTTON");
buttonClear.addEventListener("click", clearDatas);
var buttonClearT = document.createTextNode("Clear");
buttonClear.appendChild(buttonClearT);
form.appendChild(buttonClear);
var phoneNumberT = document.createElement("P");
form.appendChild(phoneNumberT);
var bayNumberT = document.createElement("P");
form.appendChild(bayNumberT);
//SAVE BUTTON//
function saveDatas() {
tablePhoneNumberTx.textContent = phoneNumber.value;
bayNumberT.textContent = bayNumber.value;
}
//CLEAR BUTTON//
function clearDatas() {
tablePhoneNumberTx.textContent = "";
bayNumberT.textContent = "";
}
//TABLE//
let body = document.body;
let tbl = document.createElement("table");
tbl.style.textAlign = "center";
tbl.style.margin = "auto";
let tablePhoneNumberTx = tbl.insertRow();
let tablePhoneNumber = tablePhoneNumberTx.insertCell();
tablePhoneNumber.appendChild(document.createTextNode(`Phone Number`));
tablePhoneNumberTx.appendChild(document.createTextNode(phoneNumber.value));
tablePhoneNumber.style.border = "1px solid black";
tablePhoneNumber.style.width = "250px";
tablePhoneNumberTx.style.border = "1px solid black";
tablePhoneNumberTx.style.background = "250px";
form.appendChild(tbl);
P.S. Its a TamperMonkey Script so, must be everything in JS
some sort of code factorization you could use, but since you wrote "only JS" I wonder why you are referencing CSS classes?
const newEl = ( tag, styling={}, attrbs={} ) =>
{
let elm = document.createElement(tag)
for(let key in styling) elm.style[key] = styling[key]
for(let key in attrbs) elm[key] = attrbs[key]
return elm
};
let myDiv = document.body
.appendChild
( newEl('div'
, {width:'200px', margin:'auto'}
, {className:'toto', textContent:'hello world'}
) );
console.log( myDiv )

Append a button to an input with js

var body = document.getElementsByTagName("body")[0];
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
p1.innerHTML = "Half this number: ";
p2.innerHTML = "Percentage of the number: ";
p3.innerHTML = "Area of the circle: ";
var halfNumber = document.createElement("input");
var percentage = document.createElement("input");
var circleArea = document.createElement("input");
halfNumber.innerHTML = "number";
percentage.innerHTML = "number";
circleArea.innerHTML = "number";
var c1 = document.createElement("button");
var c2 = document.createElement("button");
var c3 = document.createElement("button");
c1.value = "Calculate";
c2.value = "Calculate";
c3.value = "Calculate";
p1.appendChild(halfNumber);
p2.appendChild(percentage);
p3.appendChild(circleArea);
halfNumber.appendChild(c1);
percentage.appendChild(c2);
circleArea.appendChild(c3);
body.appendChild(p1);
body.appendChild(p2);
body.appendChild(p3);
the buttons c1,2,3 should append to the inputs, but for some reason, it doesn't.
I thought that the problem was the order of the appends but apparently it's not that.
<input> elements are void elements - they can't have children. So when you do
halfNumber.appendChild(c1);
since halfNumber (and the other 2) are input elements, nothing gets appended.
You could use insertAdjacentElement instead:
halfNumber.insertAdjacentElement('afterend', c1);
But the buttons still don't have any text, because you're assigning to their .values. Only input-like elements have .values. Assign to their textContent instead:
c1.textContent = "Calculate";
var body = document.getElementsByTagName("body")[0];
var p1 = document.createElement("p");
var p2 = document.createElement("p");
var p3 = document.createElement("p");
p1.innerHTML = "Half this number: ";
p2.innerHTML = "Percentage of the number: ";
p3.innerHTML = "Area of the circle: ";
var halfNumber = document.createElement("input");
var percentage = document.createElement("input");
var circleArea = document.createElement("input");
halfNumber.innerHTML = "number";
percentage.innerHTML = "number";
circleArea.innerHTML = "number";
var c1 = document.createElement("button");
var c2 = document.createElement("button");
var c3 = document.createElement("button");
c1.textContent = "Calculate";
c2.textContent = "Calculate";
c3.textContent = "Calculate";
p1.appendChild(halfNumber);
p2.appendChild(percentage);
p3.appendChild(circleArea);
halfNumber.insertAdjacentElement('afterend', c1);
percentage.insertAdjacentElement('afterend', c2);
circleArea.insertAdjacentElement('afterend', c3);
body.appendChild(p1);
body.appendChild(p2);
body.appendChild(p3);
Other improvements you can make:
Instead of document.getElementsByTagName("body")[0]; use document.body
Use a function which creates a <p>, a label for it, an input, and a button at once, to make things DRY
Unless you're deliberately setting/retrieving HTML markup, use .textContent instead of .innerHTML, to be faster, safer, and more semantically appropriate
var body = document.body;
const makeSection = (labelText) => {
const p = body.appendChild(document.createElement('p'));
p.textContent = labelText;
p.appendChild(document.createElement('input'));
p.appendChild(document.createElement('button')).textContent = 'Calculate';
};
makeSection("Half this number: ");
makeSection("Percentage of the number: ");
makeSection("Area of the circle: ");

Select element in webview not working

I Have created a modal inside the listview having input fields and select element. This list is shown up in webview of android. When I am clicking the input field, I am able to change the value inside it but when I am clicking the select field nothing happens even though I have the data inside that select list and even it is focussed by click listener. Can anyone please help me with it?
I am sharing the sample code:-
var modalInList = function(){
var originalList = document.getElementsByClassName("tt-menu");
var divElement = document.createElement("div")
divElement.id = "divToAdd";
var listElement = document.createElement("li");
listElement.id = "listToAdd";
var inputFieldForDose = document.createElement("input");
var inputFieldForFrequency = document.createElement("select");
var inputFieldForDays = document.createElement("input");
var take = document.createElement("span");
var tablet = document.createElement("span");
var forData = document.createElement("span");
var days = document.createElement("span");
take.innerHTML = "Take"
tablet.innerHTML = "Tablet"
forData.innerHTML = "for"
days.innerHTML = "Days"
divElement.appendChild(take);
inputFieldForDose.id = "doseList";
inputFieldForFrequency.id = "frequencyList";
inputFieldForDays.id = "daysList";
inputFieldForDose.contentEditable = 'true'
inputFieldForFrequency.contentEditable = 'true'
inputFieldForDays.contentEditable = 'true'
inputFieldForDose.style.color = "black";
inputFieldForDose.style.width = "45px";
inputFieldForDose.style.marginLeft = "1px";
inputFieldForDose.style.marginRight = "1px";
inputFieldForDose.style.textAlign = "center";
inputFieldForDose.style.padding = "1px";
inputFieldForDose.style.border = "solid 1px #c9c9c9";
inputFieldForFrequency.style.color = "black";
inputFieldForFrequency.style.width = "auto";
inputFieldForFrequency.style.marginLeft = "1px";
inputFieldForFrequency.style.marginRight = "1px";
inputFieldForFrequency.style.padding = "1px";
inputFieldForFrequency.style.border = "solid 1px #c9c9c9";
inputFieldForDays.style.color = "black";
inputFieldForDays.style.width = "45px";
inputFieldForDays.style.marginLeft = "1px";
inputFieldForDays.style.marginRight = "1px";
inputFieldForDays.style.marginTop = "2px";
inputFieldForDays.style.textAlign = "center";
inputFieldForDays.style.padding = "1px";
inputFieldForDays.style.border = "solid 1px #c9c9c9";
inputFieldForDose.setAttribute('type', 'number');
inputFieldForDays.setAttribute('type', 'number');
if (inputFieldForFrequency.selectedIndex == -1) {
var start = '';
var len = prescriptionFrequenciesData.length;
for (var i = 0; i < len; i++) {
start += '<option value="' + prescriptionFrequenciesData[i].value + '">' + prescriptionFrequenciesData[i].title;
}
inputFieldForFrequency.innerHTML = start;
}
inputFieldForFrequency.required = true;
divElement.appendChild(inputFieldForDose);
divElement.appendChild(tablet);
divElement.appendChild(inputFieldForFrequency);
divElement.appendChild(forData);
divElement.appendChild(inputFieldForDays);
divElement.appendChild(days);
listElement.appendChild(divElement);
originalList[0].prepend(listElement);
inputFieldForDose.addEventListener('click', function(){
editFieldCheck = true;
console.log("clicked");
inputFieldForDose.focus();
$(".tt-menu").show();
inputFieldForDose.focus();
})
inputFieldForFrequency.addEventListener('click', function(){
editFieldCheck = true;
console.log("clicked");
inputFieldForFrequency.focus();
$(".tt-menu").show();
inputFieldForFrequency.focus();
})
inputFieldForDays.addEventListener('click', function(){
editFieldCheck = true;
console.log("clicked");
inputFieldForDays.focus();
$(".tt-menu").show();
inputFieldForDays.focus();
})
}
Here inputFieldForDays is the element for element. and $(".tt-menu") is used for bloodhound.js list

Problems setting style tag to a div

I am creating something with JS and I cannot seem to add the style tag to a div that I created via javascript (I am not making a class for css for a reason do not suggest it) here is my code
function createForm()
{
var container = document.getElementsByClassName("container-fluid");
var formElement = document.createElement("form");
var inputName = document.createElement("input");
var inputEvent = document.createElement("input");
var inputTime = document.createElement("input");
var sendWithTimer = document.createElement("input");
var sendWithoutTimer = document.createElement("input");
var divContainer = document.createElement("div");
formElement.className = "form";
divContainer.className = "enforce-styles";
inputName.className = "name";
inputEvent.className = "event";
inputTime.className = "time";
sendWithTimer.className = "sendWithTimer";
sendWithoutTimer.className = "sendWithoutTimer";
inputName.setAttribute('type', "text");
inputEvent.setAttribute('type', "text");
inputTime.setAttribute('type', "text");
inputName.setAttribute('placeholder', "Name");
inputEvent.setAttribute('placeholder', "Event");
inputTime.setAttribute('placeholder', "Time");
sendWithTimer.setAttribute('type', "button");
sendWithoutTimer.setAttribute('type', "button");
sendWithTimer.setAttribute('value', "Timer");
sendWithoutTimer.setAttribute('value', "No timer");
formElement.appendChild(inputName);
formElement.appendChild(inputEvent);
formElement.appendChild(inputTime);
divContainer.appendChild(sendWithTimer);
divContainer.appendChild(sendWithoutTimer);
for (var formElementStyles = 0; formElementStyles < formElement.length; formElementStyles++)
{
formElement[formElementStyles].style.display = "-webkit-flex";
formElement[formElementStyles].style.display = "flex";
formElement[formElementStyles].style.webkitFlexDirection = "column";
formElement[formElementStyles].style.flexDirection = "column";
formElement[formElementStyles].style.position = "relative";
formElement[formElementStyles].style.top = 0;
formElement[formElementStyles].style.left = 40 + "%";
formElement[formElementStyles].style.padding = 0.6 + "em";
formElement[formElementStyles].style.margin = 1 + "em";
}
for (var divContainerStyles = 0; divContainerStyles < divContainer.length; divContainerStyles++)
{
divContainer[divContainerStyles].style.display = "-webkit-flex";
divContainer[divContainerStyles].style.display = "flex";
divContainer[divContainerStyles].style.webkitFlexDirection = "column";
divContainer[divContainerStyles].style.flexDirection = "column";
divContainer[divContainerStyles].style.position = "relative";
divContainer[divContainerStyles].style.top = 0;
divContainer[divContainerStyles].style.left = 40 + "%";
divContainer[divContainerStyles].style.padding = 0.6 + "em";
divContainer[divContainerStyles].style.margin = 1 + "em";
divContainer[divContainerStyles].style.height = 10 + "em";
}
container[0].appendChild(formElement);
container[0].appendChild(divContainer);
}
I cannot seem to get the second for loop to place the style tags. The div just appears with nothing but a class name which was set above. But I cannot get the styles on there. The styles are for two buttons inside a form I am inserting into a clients website. How can I get this to work? What am I doing wrong?
Your code does not apply the style to the input fields, because divContainer.length does not exist, neither does divContainer[divContainerStyles]. divContainer is an div Object and has no length attribute (as opposed to the form element, which does have a length attribute) so that's why it never gets into the second loop.
Your code produces the following error: https://jsfiddle.net/tdbju0ud/
Instead, you should check for the length of divContainer.childNodes and apply the styles to those.
for (var divContainerStyles = 0; divContainerStyles < divContainer.childNodes.length; divContainerStyles++)
{
divContainer.childNodes[divContainerStyles].style.display = "-webkit-flex";
...
}
A working test in: https://jsfiddle.net/Lvq6hvxd/
This will work- divContainer[divContainerStyles].setAttribute('style', <your styles>)
Use childNodes to get the child elements of the div container.
like
var nodes = divContainer.childNodes
Find out the length of this nodes array object to find out the child elements count of the div.
Here is the corrected code :
var container = document.getElementsByClassName("container-fluid");
var formElement = document.createElement("form");
var inputName = document.createElement("input");
var inputEvent = document.createElement("input");
var inputTime = document.createElement("input");
var sendWithTimer = document.createElement("input");
var sendWithoutTimer = document.createElement("input");
var divContainer = document.createElement("div");
formElement.className = "form";
divContainer.className = "enforce-styles";
inputName.className = "name";
inputEvent.className = "event";
inputTime.className = "time";
sendWithTimer.className = "sendWithTimer";
sendWithoutTimer.className = "sendWithoutTimer";
inputName.setAttribute('type', "text");
inputEvent.setAttribute('type', "text");
inputTime.setAttribute('type', "text");
inputName.setAttribute('placeholder', "Name");
inputEvent.setAttribute('placeholder', "Event");
inputTime.setAttribute('placeholder', "Time");
sendWithTimer.setAttribute('type', "button");
sendWithoutTimer.setAttribute('type', "button");
sendWithTimer.setAttribute('value', "Timer");
sendWithoutTimer.setAttribute('value', "No timer");
formElement.appendChild(inputName);
formElement.appendChild(inputEvent);
formElement.appendChild(inputTime);
divContainer.appendChild(sendWithTimer);
divContainer.appendChild(sendWithoutTimer);
for (var formElementStyles = 0; formElementStyles < formElement.length; formElementStyles++) {
formElement[formElementStyles].style.display = "-webkit-flex";
formElement[formElementStyles].style.display = "flex";
formElement[formElementStyles].style.webkitFlexDirection = "column";
formElement[formElementStyles].style.flexDirection = "column";
formElement[formElementStyles].style.position = "relative";
formElement[formElementStyles].style.top = 0;
formElement[formElementStyles].style.left = 40 + "%";
formElement[formElementStyles].style.padding = 0.6 + "em";
formElement[formElementStyles].style.margin = 1 + "em";
}
var divChildNodes = divContainer.childNodes;
for (var divContainerStyles = 0; divContainerStyles < divChildNodes.length; divContainerStyles++) {
divChildNodes[divContainerStyles].style.display = "-webkit-flex";
divChildNodes[divContainerStyles].style.display = "flex";
divChildNodes[divContainerStyles].style.webkitFlexDirection = "column";
divChildNodes[divContainerStyles].style.flexDirection = "column";
divChildNodes[divContainerStyles].style.position = "relative";
divChildNodes[divContainerStyles].style.top = 0;
divChildNodes[divContainerStyles].style.left = 40 + "%";
divChildNodes[divContainerStyles].style.padding = 0.6 + "em";
divChildNodes[divContainerStyles].style.margin = 1 + "em";
divChildNodes[divContainerStyles].style.height = 10 + "em";
}
container[0].appendChild(formElement);
container[0].appendChild(divContainer);

innerHTML not showing up when added input element dynamically

I am trying to add an <input> element using Javascript. However, the innerHTML is not showing up. Below is my code:
function addElements()
{
container = document.getElementById("duration"); //a div container
var input1 = document.createElement("input");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
input1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
input2.innerHTML = "months";
container.appendChild(input1);
container.appendChild(input2);
}
The result of this code only produces two number input fields without the innerHTML. Is there anything wrong with my code?
Input elements don't have inner content you can set with innerHTML. Instead set value property:
input1.value = "years";
However, it seems that in your case you want to set placeholder:
input1.setAttribute("placeholder", "years");
or you can set corresponding property as well:
input1.placeholder = "years";
I think what you try to achieve is [label][input] in this case you have to add 2 new more elements on page.
function addElements()
{
container = document.getElementById("duration"); //a div container
var label1 = document.createElement("label");
var input1 = document.createElement("input");
var label2 = document.createElement("label");
var input2 = document.createElement("input");
input1.type = "number";
input1.min = "0";
input1.max = "10";
input1.required = true;
label1.innerHTML = "years";
input2.type = "number";
input2.min = "0";
input2.max = "12";
input2.required = true;
label2.innerHTML = "months";
container.appendChild(label1);
container.appendChild(input1);
container.appendChild(label2);
container.appendChild(input2);
}
addElements();
<div id="duration" />

Categories