innerHTML not showing up when added input element dynamically - javascript

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" />

Related

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: ");

Appending created elements to different divs in 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.

Array reversed when it's sent using the form

I'm sending 3 arrays with checkboxes (checked and not) using a form to a PHP page, trying to do an Insert in a MySQL database. When I send an array with length = 1, it inserts just fine, but arrays with length superior to 1 are shown (and insert) reversed when 2 or 3 checkboxes are checked, occupying index 0 of the array, being that it was at index 1 at first.
I'm using WAMP 3.1.7 64 bits, PHP 7.2.14 and Brackets. The arrays are called "electricidad", "proyector" and "wifi". I create the checkboxes with a button using the function nuevaSala (element), function checkboxElegido() is to change the value of checked checkboxes (no is the default).
<script>
var instancia = 0;
function nuevaSala(element){
instancia++;
var newDiv = document.createElement("DIV");
newDiv.name = "nuevasSalasDiv[]";
newDiv.id = "nuevasSalas"+instancia;
var newLabel = document.createElement("LABEL");
newLabel.id = "Sala"+instancia;
newLabel.innerHTML = "Sala "+instancia;
var newInput = document.createElement("INPUT");
newInput.id = "sala"+instancia;
newInput.name = "nombreSala[]";
newInput.type = "text";
var newLabel1 = document.createElement("LABEL");
newLabel1.id = "Capacidad"+instancia;
newLabel1.innerHTML = "Capacidad";
var newInput1 = document.createElement("INPUT");
newInput1.id = "capacidad"+instancia;
newInput1.name = "capacidad[]";
newInput1.type = "number";
var newCheckbox = document.createElement("input");
newCheckbox.type = "checkbox";
newCheckbox.name = "electricidad[]";
newCheckbox.id = "electricidad"+instancia;
newCheckbox.value = "no";
newCheckbox.setAttribute("onclick", "checkboxElegido()");
newCheckbox.setAttribute("style", "float: right");
var newCheckbox1 = document.createElement("input");
newCheckbox1.type = "checkbox";
newCheckbox1.name = "wifi[]";
newCheckbox1.id = "wifi"+instancia;
newCheckbox1.value = "no";
newCheckbox1.setAttribute("onclick", "checkboxElegido()");
newCheckbox1.setAttribute("style", "float: right");
var newCheckbox2 = document.createElement("input");
newCheckbox2.type = "checkbox";
newCheckbox2.name = "proyector[]";
newCheckbox2.id = "proyector"+instancia;
newCheckbox2.value = "no";
newCheckbox2.setAttribute("onclick", "checkboxElegido()");
newCheckbox2.setAttribute("style", "float: right");
var newLabelElec = document.createElement("LABEL");
newLabelElec.innerHTML = "Electricidad";
newLabelElec.setAttribute("style", "float: right");
var newLabelProy = document.createElement("LABEL");
newLabelProy.innerHTML = "Proyector";
newLabelProy.setAttribute("style", "float: right");
var newLabelWifi = document.createElement("LABEL");
newLabelWifi.innerHTML = "Wifi";
newLabelWifi.setAttribute("style", "float: right");
document.getElementById("salaId").appendChild(newDiv);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabel);
document.getElementById("nuevasSalas"+instancia).appendChild(newInput);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabel1);
document.getElementById("nuevasSalas"+instancia).appendChild(newInput1);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelElec);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelProy);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox2);
document.getElementById("nuevasSalas"+instancia).appendChild(newLabelWifi);
document.getElementById("nuevasSalas"+instancia).appendChild(newCheckbox1);
document.getElementById("nuevasSalas"+instancia).appendChild(document.createElement("BR"));
}
</script>
<script>
function checkboxElegido(){
var proy = document.getElementsByName("proyector[]");
var wifi = document.getElementsByName("wifi[]");
var elec = document.getElementsByName("electricidad[]");
function valores(item){
if(item.checked){
item.setAttribute("value", "si");
} else if(!item.checked){
item.setAttribute("value", "no");
}
}
proy.forEach(valores);
wifi.forEach(valores);
elec.forEach(valores);
}
</script>
If the array has lenght 2, and the checked checkbox is "electricidad" in index 0 and checked in index 1 are "wifi", "electricidad" and "proyector", I expect this:
[0] = "electricidad" => si, "wifi" => no, "proyector" => no
[1] = "electricidad" => si, "wifi" => si, "proyector" => si
but I got this:
[0] = "electricidad" => si, "wifi" => si, "proyector" => si
[1] = "electricidad" => si
Beforehand, thank you!

Using onclick in javascript to create a new div inside a div created using onclick itself?

I created a div consisting of radio button inputs using onclick from a radio button input inside a form in php and then i again attempted to create another div using onclick from inside this created div but only the outer div is being created. Would like to know where i am wrong..
<input id="sub" type="radio" name="opt1" value="2" onclick="createDiv4()"> Academic User<br/>
function createDiv4() {
if(document.getElementById("acad_")==null)
{
var divi = document.createElement("div");
divi.id="acad_";
divi.style.height="100px";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.onclick="createDiv4_1()";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("Technical Institute");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
ip2.onclick="createDiv4_1()";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("School");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("acad_");
divi1.parentNode.removeChild(divi1);
}
}
</script>
<script>
function createDiv4_1() {
if(document.getElementById("school")==null)
{
var divi = document.createElement("div");
divi.id="school";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User for Workshop :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("School Student");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("Teacher");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
var b2 = document.createElement("BR");
divi.appendChild(b2);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe3 = document.createElement("label");
var labe_val3 = document.createTextNode("Parent");
labe3.appendChild(labe_val3);
divi.appendChild(labe3);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("school");
divi1.parentNode.removeChild(divi1);
}
}
</script>
You arent calling the functions properly. Instead of :
ip.onclick= "createDiv4_1()";
This is only a string, it won't call it. You put it in quotes in the HTML but in JavaScript you don't need to. Also get rid of the parenthesis in JS. So use this :
ip.onclick= createDiv4_1;
Working fiddle : https://jsfiddle.net/thatOneGuy/xgvqwcq4/2/
I added a div with ID contain for this to work too.
according to your question title you have two option.
forget about onclikc inside the html and use normal js
document.getElementById("secondDiv").addEventListener("click", function () {
newFunctionI();
})
/*JQ version*/
$("#secondDiv").on("click", function () {
newFunctionI();
})
second way is: use jquery append() or html();
function yourFunctionI() {
$("#ID").append("<div id='secondDiv' onclick='newFunction()'> new </div>")
}

Creating an object with 4 button on javascript

I created an object on js with 4 buttons, but it's not showing,
this is my code:
function Keyboard() {
this.plus = document.createElement("input");
this.plus.type = "submit";
this.plus.value = "A";
this.minus = document.createElement("input");
this.minus.type = "submit";
this.minus.value = "B";
this.multi = document.createElement("input");
this.multi.type = "submit";
this.multi.value = "C";
this.divide = document.createElement("input");
this.divide.type = "submit";
this.divide.value = "D";
}
var k = new Keyboard();
document.body.appendChild(k);
I will add the onClick later, but why is this not showing?
Thanks!
Your Keyboard constructs a simple JavaScript object with 4 properties, but not a DOM object. Later, you try to append a simple JavaScript object to your document.
First, you need to create DOM element using document.createElement.
Second, you don't need new keyword here at all.
Third, you don't need to set subitems as properties. You append them to a parent object, and it is enough.
Try the following code:
function CreateKeyboard() {
var t = document.createElement("div");
var plus = document.createElement("input");
plus.type = "submit";
plus.value = "A";
t.appendChild(plus);
var minus = document.createElement("input");
minus.type = "submit";
minus.value = "B";
t.appendChild(minus);
var multi = document.createElement("input");
multi.type = "submit";
multi.value = "C";
t.appendChild(multi);
var divide = document.createElement("input");
divide.type = "submit";
divide.value = "D";
t.appendChild(divide);
return t;
}
document.body.appendChild(CreateKeyboard());
By the way, you can avoid code repetition. For example, by utilizing Array.prototype.forEach:
function CreateKeyboard() {
var t = document.createElement("div");
['A', 'B', 'C', 'D'].forEach(function(l) {
var elem = document.createElement("input");
elem.type = "submit";
elem.value = l;
t.appendChild(elem);
});
return t;
}
document.body.appendChild(CreateKeyboard());
This should work:
<script type="text/javascript">
function createSubmitButton(val) {
var el = document.createElement("input");
el.type = "submit";
el.value = val;
document.body.appendChild(el);
}
createSubmitButton("A");
createSubmitButton("B");
createSubmitButton("C");
createSubmitButton("D");
</script>
Make sure you place the script tag at the bottom of the html code, right before the ending body tag.
k is not type of Node. Append only Node elements you have created.
var k = new Keyboard();
document.body.appendChild(k.plus);
document.body.appendChild(k.minus);
document.body.appendChild(k.multi);
document.body.appendChild(k.divide);

Categories