JavaScript Table content Add and Delete - javascript

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 )

Related

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.

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

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

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

Obtain values from a form text field

I created a form dynamically when onclick a button "Add Record" in a form. The new form is created and assigned to a div, after rendering this form I can't get any of the values in textboxes.
while testing I tried many ways to get the form and elements and it returns undefined. The name of the form is "addrec_form".
I tried
var address1 = document.forms.addrec_form.address.value
var address1 = document.forms['addrec_form'].elements['address']
assigned it to a variable and then use alert("value of address is: " + address1)
all this returns document.forms.addrec_from is undefined. While testing with firebug I set up the button onclick of this new form to just show an alert with just a string for testing purposes, but when debugging although the button onclick is not click is still in the process of rendering it displays the alert message then finishes and all looks okay but can't access the values in the form.
Can some one explain to me how can I get this working? I might have code something wrong, but I did consult my books and samples I can't seem to figure out.
This is my code:
function addRec(){
var browserName = whichBrs();
//var outterDiv =
document.getElementById("gridDiv").style.visibility="visible";
if(document.getElementById("AddRecords").style.visibility == "hidden")
{
document.getElementById("AddRecords").style.visibility = "visible"
}
var tbl = document.createElement("table");
tblbody = document.createElement("tbody");
// applies the css to the element i.e. element is tbl class is list2
browserDetect(tbl, "list2");
var tr1 = document.createElement("tr");
tr1.style.background = "#e8edff";
var th1 = document.createElement("th");
browserDetect(th1, "cancelimgX");
tr1.appendChild(th1);
var img1 = document.createElement("img");
img1.setAttribute("src", "images/close.png");
img1.onclick = function(){setDivVisibility(); return false;};
img1.setAttribute("title", "Close Window");
img1.style.cursor="pointer";
img1.style.height="16px";
img1.style.border="0px"
th1.appendChild(img1);
var tr2 = document.createElement("tr");
tr2.style.background = "#e8edff";
var td1 = document.createElement("td");
td1.style.padding = "0.5em 0.5em 0.5em 0.5em";
var fieldset1 = document.createElement("fieldset");
fieldset1.style.padding = "0 0 0.5em 0";
fieldset1.style.border = "1px solid #001685";
fieldset1.style.background = "#e8edff";
var legend1 = document.createElement("legend");
legend1.background = "#e8edff";
var legendtxt = document.createTextNode("Adding a Record");
var fontA = document.createElement("font");
fontA.style.color = "#001685";
fontA.style.fontWeight = "bolder";
fontA.appendChild(legendtxt);
legend1.appendChild(fontA);
var form1 = document.createElement("form");
form1.setAttribute("method", "post");
form1.setAttribute("name", "addrec_form");
form1.setAttribute("id", "addrec_form");
var tbl2 = document.createElement("table");
var tbl2body = document.createElement("tbody");
browserDetect(tbl2, "tblAddRec");
var address1 = "Address";
var city1 = "City";
var hardware_number1 = "Hardware Number";
var hardware_status1 = "Hardware Status";
var software_status1 = "software Status";
var premise1 = "Premise";
var service_point1 = "Service Point";
var val = "Create Record";
// creating labels and textboxes
genLblBxs(address1,tbl2body, "address");
genLblBxs(city1,tbl2body, "city");
genLblBxs(hardware_number1,tbl2body, "hardware_number1");
genLblBxs(hardware_status1,tbl2body, "hardware_status1");
genLblBxs(software_status1,tbl2body, "software_status1");
genLblBxs(premise1,tbl2body, "premise");
genLblBxs(service_point1,tbl2body, "service_point");
genFooter(val, tbl2body);
tbl2.appendChild(tbl2body);
form1.appendChild(tbl2);
fieldset1.appendChild(legend1);
fieldset1.appendChild(form1);
td1.appendChild(fieldset1);
tr2.appendChild(td1);
tblbody.appendChild(tr1);
tblbody.appendChild(tr2);
tbl.appendChild(tblbody);
var addrecorddiv = document.getElementById("AddRecords");
addrecorddiv.appendChild(tbl);
}
function genFooter(val, tbl2body)
{
var tr = document.createElement("tr");
var td = document.createElement("td");
td.colSpan = "2";
td.align="right";
td.vAlign="bottom";
td.height = "35px";
var btnCreateRec = document.createElement("INPUT");
btnCreateRec.type="button";
btnCreateRec.id = "btnRec";
btnCreateRec.name = "btnRec";
btnCreateRec.value = val;
btnCreateRec.style.color = "#FFFFFF";
btnCreateRec.style.border = "1px solid";
btnCreateRec.style.backgroundColor = "#416ADC";
btnCreateRec.height = "20";
btnCreateRec.onmouseover = function(){ document.getElementById("btnRec").style.backgroundColor = "#001685"; return false;};
btnCreateRec.onmouseout = function(){ document.getElementById("btnRec").style.backgroundColor = "#416ADC"; return false;};
// THIS IS WHERE PASSING THE ARRAY OF TEXTBOXES IS PASSED TO A FUNCTION FOR FURTHER PROCESSING
// THIS IS WHAT I CAN'T FIGURE OUT
btnCreateRec.onmouseclick = function(){insertRequest(document.forms.addrec_form, 'INSERT_ROW');};
td.appendChild(btnCreateRec);
tr.appendChild(td);
tbl2body.appendChild(tr);
}
function genLblBxs(value_id, tbl2body, box_id)
{
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.setAttribute('noWrap','true');
td1.align="left";
td1.width="15%";
td1.vAlign="baseline";
td1.style.padding = "0.5em 0 0 0.5em";
var lbl = document.createTextNode(value_id);
var font1 = document.createElement("font");
font1.style.color = "navy";
font1.appendChild(lbl);
value_id = value_id.toLowerCase(); ;
var td2 = document.createElement("td");
td2.align = "left";
td2.style.padding = "0 0.5em 0 0.5em";
var txtBox = document.createElement("INPUT");
txtBox.type="text";
txtBox.id =box_id;
txtBox.name = box_id;
txtBox.size = "37";
txtBox.color = "navy";
txtBox.style.border = "1px solid #C3D5FF";
td1.appendChild(font1);
td2.appendChild(txtBox);
tr.appendChild(td1);
tr.appendChild(td2);
tbl2body.appendChild(tr);
}
Try stripping down your code first to just include the dynamic adding of the form and getting the values in the textbox to make your code easier for everybody else to understand and it will also make it easier for you to debug your code. Don't forget to backup the original code.
I tried copying and pasting your code onto an empty page with a container div defined. It failed on a couple of missing functions (whichBrs and browserDetect), which I presume you have defined elsewhere. Then, there's no such thing as onmouseclick, which I replaced with onclick. After that it worked ok in IE8 and FF3: alert(document.forms.addrec_form.address.value) within insertRequest showed me whatever I typed into the address field.
Did you try using firebug(in FF) to determine if there are javascript errors on your page?
Try debugging and looking at the DOM tree in its views.
I apologize for providing so much code, this is my first time
requesting for assistance, I'll be more diligent next time.
Thanks to all for your suggestions.
Originally the addRec() was called by onclick on a button in a form/table,
then this form/table was rendered and the onclick was not working to pass
the textboxes values.
I managed to get it working as follows:
Created a function to call addRec(), after that I added
document.getElementById("btnRec").onclick = function(){insertRequest(document.forms.addrec_form, 'INSERT_ROW');};
Thanks again...

Categories