Creating an object with 4 button on javascript - 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);

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 )

How to create multiple paragraphs with Javascript with shorter code?

I want to create multiple paragraphs with each two inputfield with Javascript.
I wanted to know, if there is a way to have a shorter code but the same result?
It should have the same result like this but with a shorter code:
var para1 = document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
var element = document.getElementById("div1");
element.appendChild(para1);
var para2 = document.createElement("p");
var i3 = document.createElement("input");
var i4 = document.createElement("input");
para2.appendChild(i3);
para2.appendChild(i4);
var element = document.getElementById("div1");
element.appendChild(para2);
var para3 = document.createElement("p");
//etc.
<div id="div1"></div>
I could not think of any other solution than using a for loop 😁
This definitely reduces the code by half length though.
numberOfParagraphs = 3
for(let i = 0; i< numberOfParagraphs;i++){
var para= document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para.appendChild(i1);
para.appendChild(i2);
document.getElementById("div1").appendChild(para);
}
<div id="div1"></div>
Wrap your code into a function
function createPara() {
var para1 = document.createElement("p");
var i1 = document.createElement("input");
var i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
var element = document.getElementById("div1");
element.appendChild(para1);
}
Call the function n times
createPara()
createPara()
Additionally you can pass params such as class, id etc.
well the way you have it written, you are executing the exact same code multiple times. why not put it in a function?
createPara();
createPara();
createPara();
//etc.
function createPara() {
var para2 = document.createElement("p");
var i3 = document.createElement("input");
var i4 = document.createElement("input");
para2.appendChild(i3);
para2.appendChild(i4);
var element = document.getElementById("div1");
element.appendChild(para2);
}
Create a document fragment and append it to DIV instead of creating individual elements.
In the current setup, HTML elements will reflow each time you append any element.
With DocumentFragment you can save multiple reflows as it reflows only once when attached.
Please refer https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment for information.
wrap your code into a function and give it number of para :
function createPara(n) {
let parentDiv = document.getElementById("div1")
for(let i =0; i<n; i++){
let para = document.createElement("p");
let i1 = document.createElement("input");
let i2 = document.createElement("input");
para1.appendChild(i1);
para1.appendChild(i2);
parentDiv.appendChild(para);
}
}
}
Call the function and give it the number u want to repeat for exemple 5 time :
createPara(5)
you can also give it the number of inputs
I thought I would do something for a more general case, but might have gotten a bit carried away; anyway:
const new_children = [
{ tag: 'p', children: [
{ tag: 'input' },
{ tag: 'input' },
] },
];
const element_for_def = (def) => {
const element = document.createElement(def.tag);
if(def.children && def.children.length > 0)
append_children_to_ele(element, def.children);
return element;
};
const append_to_element = (parent) => (child) => parent.appendChild(child);
const append_children_to_ele = (parent, children) =>
children
.map(element_for_def)
.forEach(append_to_element(parent));
const three_new_children = [1,2,3].reduce(acc => acc.concat(new_children), []);
append_children_to_ele(document.getElementById("div1"), three_new_children);
<div id="div1"></div>
ma is a reference to an element object which you want to create multiple paragraphs.
I use 10 for multiple paragraphs line. You can use your required number.
let ma = document.getElementById("multiple-para").innerHTML;
for(var i =0; i<10; i++){
document.write(ma + "<br>");
}

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

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>")
}

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