what is error in this js code - javascript

var RowNumber = row.rowIndex;
alert(RowNumber);
var a = document.createElement('a');
a.textContent = 'Remove';
a.style.cursor = 'pointer';
//a.href = "javascript: document.getElementById(tblId).deleteRow(0);";
a.setAttribute("onclick","alert(RowNumber)");
cell1.appendChild(a);
firebug say 'RowNumber is not defined' but i have defined RowNumber above.
Also alrting the RowNumber variable.
And my complete function is =
function addRowToTable(tblId,icOptionArray,leavRowFromBottom,selectedValue,selectedQuantity)
{
var tbl = document.getElementById(tblId);
var lastRow = tbl.rows.length - (leavRowFromBottom + 0);
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
// var iteration = lastRow + 1;
var row = tbl.insertRow(lastRow);
// cell 0
var cell0 = row.insertCell(0);
cell0.align='right';
var el = document.createElement('label');
el.textContent = 'IC Chips :';
cell0.appendChild(el);
//cell 1
var cell1 = row.insertCell(1);
var selector = document.createElement('select');
selector.id = 'icchips';
selector.name = 'icchips[]';
selector.style.width = '200px';
//alert(selector);
for (var key in icOptionArray)
{
if(key == 'containsValue') continue;
var option = document.createElement('option');
if(key == selectedValue)
option.selected = true;
option.value = key;
option.appendChild(document.createTextNode(icOptionArray[key]));
selector.appendChild(option);
}
cell1.appendChild(selector);
var space = document.createTextNode(' ');
cell1.appendChild(space);
var lbl = document.createElement('label');
lbl.textContent = 'Qty :';
cell1.appendChild(lbl);
var selector = document.createElement('select');
selector.id = 'additional_quantity';
selector.name = 'additional_quantity[]';
for (var key in QUANTITIES_ARR)
{
if(key == 'containsValue') continue;
var option = document.createElement('option');
if(key == selectedQuantity)
option.selected = true;
option.value = key;
option.appendChild(document.createTextNode(QUANTITIES_ARR[key]));
selector.appendChild(option);
}
cell1.appendChild(selector);
var space = document.createTextNode(' ');
cell1.appendChild(space);
var RowNumber = row.rowIndex;
alert(RowNumber);
var a = document.createElement('a');
a.textContent = 'Remove';
a.style.cursor = 'pointer';
//a.href = "javascript: document.getElementById(tblId).deleteRow(0);";
a.setAttribute("onclick","alert(RowNumber)");
cell1.appendChild(a);
}

do like this
a.onclick = function(){ alert(RowNumber); };

The problem is that the local scope where RowNumber is defined is not the same as the scope wherein your onclick handler is called. The solution proposed by #jancha fixes that. His use of a closure ensures the RowNumber in the handler is the same as the one in the local scope.

RowNumber is not defined in the scope of the created element, since your using jQuery you could use:
var RowNumber = row.rowIndex;
alert(RowNumber);
var a = document.createElement('a');
a.textContent = 'Remove';
a.style.cursor = 'pointer';
//a.href = "javascript: document.getElementById(tblId).deleteRow(0);";
$(a).click(function(e){
alert(RowNumber);
});

Related

Javascript: Wait until one function in first js file is complete before running function in second file

I have 2 js file, script.js and index.js. In script.js I am returning a window object to then be used in the second js file.
function text (e) {
e = e || window.event;
let row = [];
let target = e.srcElement || e.target;
while (target && target.nodeName !== "TR"){
target = target.parentNode;
}
if(target){
let cells = target.getElementsByTagName('td');
for (let i =0; i < cells.length-2; i++){
row.push(cells[i].innerHTML)
}
}
window.data= {
last: row[0],
party:row[1],
number:row[2]
}
console.log(window.data)
};
my second js fie (index), right now, is just
alert(window.data)
It is undefined since text is a function assigned to an event listener.How can I wait until the button click/ text() is ran in the first js script, to then log/ use the window object in the second js script?
Here is full script.js
const btn = document.getElementById("addRow")
btn.addEventListener("click", addRow)
function addRow() {
let name = document.getElementById("lastName").value
let party = document.getElementById("party").value
let phone = document.getElementById("phone").value
const table = document.getElementById('table')
console.log(name, party, phone)
let elem = document.createElement('select')
let optArray = ['Table Is Ready', 'Please Come See The Host', 'Your Table Will Be Ready Soon' ]
elem.className = "select"
for (let i =0; i <optArray.length; i++){
let option = document.createElement('option');
option.value = optArray[i]
option.text = optArray[i];
elem.appendChild(option);
}
let action = document.createElement('button')
action.innerHTML = "Send Message";
action.onclick = text;
let newRow = table.insertRow(1)
let cell1 = newRow.insertCell(0)
let cell2 = newRow.insertCell(1)
let cell3 = newRow.insertCell(2)
let cell4 = newRow.insertCell(3)
let cell5 = newRow.insertCell(4)
cell1.innerHTML = name;
cell2.innerHTML = party;
cell3.innerHTML = phone;
cell4.appendChild(elem)
cell5.appendChild(action)
document.getElementById("lastName").value = ''
document.getElementById("party").value = ''
document.getElementById("phone").value = ''
}
function text (e) {
e = e || window.event;
let row = [];
let target = e.srcElement || e.target;
while (target && target.nodeName !== "TR"){
target = target.parentNode;
}
if(target){
let cells = target.getElementsByTagName('td');
for (let i =0; i < cells.length-2; i++){
row.push(cells[i].innerHTML)
}
}
window.data= {
last: row[0],
party:row[1],
number:row[2]
}
console.log(window.data)
};
I'm not sure I completely understand your question, but assuming you want to use data produced by your text() function within another JS file, the steps should be simple.
First, load the script.js [The one with the text() function] second, and have the index.js file first. Example:
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript" src="script.js"></script>
Then, when text() has finished, where you have 'console.log(window.data)', instead call a new function created in your index.js.
index.js
// ...
function text (e) {
e = e || window.event;
let row = [];
let target = e.srcElement || e.target;
while (target && target.nodeName !== "TR"){
target = target.parentNode;
}
if(target){
let cells = target.getElementsByTagName('td');
for (let i =0; i < cells.length-2; i++){
row.push(cells[i].innerHTML)
}
}
window.data= {
last: row[0],
party:row[1],
number:row[2]
}
loadedFunction(window.data);
};
script.js
// alert(window.data);
const loadedFunction = (data) => {
alert(data);
// Manipulate or use 'data' here.
}

How to fix duplication of dynamic input creation at press of hotkey

I have a legacy barcode scanning application, which is used to issue items from the store. It has a combo box which has a list of all pending orders and when the user selects an order, it will list out the items expected to be issued with their quantities. Then the user presses 'f7' as a shortcut key and a new barcode field is added dynamically and then they have to scan the barcode of the bin location and after it is validated, automatically another field for the item code is added dynamically. After the item code is validated, the quantity field is added dynamically wherein the user inputs the quantity taken from that bin location. The user presses 'f7' again and the process repeats unless they finish collecting the items.
At last, they save the order and proceeds with another order.
The problem which I am facing right now is that the number of times user selects the order and presses 'f7', that number of fields are added automatically.
Example, the first time when the page loads, the user selects the order, presses 'f7', one field for bin location is added automatically, no issue here. Now, due to some reason, the user selects a second order and presses 'f7', now 2 bin location fields are added automatically. The user selects third order and presses 'f7', now 3 bin location fields are added automatically. This goes on repeating unless the user refreshes the page and starts new.
There is a variable serial defined which I have tried resetting at the time of user selecting the order but the problem still exists. I have tried resetting the variable at different places, but the problem doesn't go away.
I have used hotkeys javascript to use 'f7' as the shortcut
https://unpkg.com/hotkeys-js#3.7.1/dist/hotkeys.js
During the HTML load, a select input box is populated with all the pending orders and the below code calls the function ValueChanged with the order number when the value is changed:
<select name="Request" onchange="ValueChanged(this);;">
The function ValueChanged builds a URL with the order number and passes an Ajax request to another page through function SendAjaxRequest which collects the required data and then another function SetValues builds a table with the data on the page. Now, this function SetValues has the shortcut function hotkeys which adds the field dynamically.
Below is the javascript code
stopEvent = function(ffevent)
{
var current_window = window;
if(current_window.event) //window.event is IE, ffevent is FF
{
//IE
current_window.event.cancelBubble = true; //this stops event propagation
current_window.event.returnValue = false; //this prevents default (usually is what we want)
}
else
{
//Firefox
ffevent.stopPropagation();
ffevent.preventDefault();
};
}
function validateAllInputBoxes(ffevent)
{
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; ++i)
if(inputs[i].type === 'text')
if(inputs[i].value === '')
{
alert("form could not be sent one input text field is empty");
stopEvent(ffevent);
}
var x = document.forms["myForm"]["Request"].value;
if (x == null || x == "") {
alert("Select GRN");
stopEvent(ffevent);
}
var inputFormDiv = document.getElementsByTagName('input').length;
if (inputFormDiv<=1) {
alert("Enter atleast one BIN Information");
stopEvent(ffevent);
}
}
function addRow() {
var myName = document.getElementById("name");
var age = document.getElementById("age");
var table = document.getElementById("myTableData");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML= '<input type="button" value = "Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(1).innerHTML= myName.value;
row.insertCell(2).innerHTML= age.value;
}
var deleteRow = function (link) {
var row = link.parentNode.parentNode;
var table = row.parentNode;
table.parentNode.removeChild(table);
}
//function deleteRow(obj) {
// var index = obj.parentNode.parentNode.rowIndex;
// var table = document.getElementById("myDynamicTable2");
// table.deleteRow(index);
//}
function addTable() {
}
function load() {
console.log("Page load finished");
}
function GetXmlHTTP() {
//first check for IE:
if (window.ActiveXObject) {
var objXML = 0;
try {
objXML = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex) {
try {
objXML = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(ex) {
alert("AJAX: your browser does not support proper XMLHTTP");
}
}
return objXML;
}
//maybe Mozilla?
if (window.XMLHttpRequest)
return new XMLHttpRequest();
//unknown browser..
alert("AJAX: unknown browser.");
return 0;
} //end function GetXmlHTTP
/*
this function send request to the given URL via
GET method.
*/
function SendAjaxRequest(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
SetValues(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest1(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues1(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function SendAjaxRequest2(strURL) {
//get xmlhttp component:
var objXML = GetXmlHTTP();
//got anything?
if (!objXML)
return false;
//attach local callback function:
objXML.onreadystatechange = function()
{
//ready?
if (objXML.readyState == 4)
{
//get status:
var status=objXML.status;
//maybe not successful?
if (status != 200)
{
// alert("AJAX: server status " + status);
}
else
{
//get response text:
var strResponse = objXML.responseText;
SetValues2(strResponse);
}
}
}
//send request:
objXML.open("GET", strURL, true);
objXML.send(null);
} //end function SendAjaxRequest
function ValueChanged(oDDL)
{
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveBIN.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
rqstnumber = selectedValue;
SendAjaxRequest(strURL);
}
}
function ValueChangedDesc(oDDL)
{
var selectedValue = oDDL.value;
selectedValueBIN = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveDesc.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime();
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest1(strURL);
}
}
function ValueChangedItem(oDDL)
{
var xperia = document.forms["myForm"]["Request"].value;
//var binival = bini.value;
var selectedValue = oDDL.value;
if (selectedValue.length > 0)
{
var strURL = "RetrieveItem.asp?value=" + selectedValue + "&ts=" + (new Date()).getTime() + "&rqn=" + xperia + "&bin=" + selectedValueBIN;
//alert(strURL);
//SetValues("Loading...|Loading...|Loading...");
SendAjaxRequest2(strURL);
}
}
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(3);
}
function SetValues1(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
var txt = document.activeElement.name;
var numb = txt.match(/\d/g);
numb = numb.join("");
var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table1 = document.createElement('TABLE');
//table1.border='1';
//var tableBody2 = document.createElement('TBODY');
//table1.appendChild(tableBody2);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'ItemCode');
input.setAttribute("id", serial+'ItemCode');
//input.setAttribute("autofocus",'True');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.onkeydown = function(){ValueChangedItem(this);};
var lblt = document.createTextNode('Item Code - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
//document.getElementById(serial+"ItemCode").focus();
var inputs1 = document.getElementById(serial+'ItemCode');
inputs1.focus();
inputs1.focus();
//inputs1.focus();
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'ItemCode') {
// alert(inputs[1].name);
//alert('arif');
//inputs[i].focus();
//break;
// }
//
//}
serial++;
} else {
}
}
function SetValues2(sRawData)
{
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//var txt = document.activeElement.name;
//var numb = txt.match(/\d/g);
//numb = numb.join("");
//var elem = document.getElementById('1ItemDesc');
//elem.value = arrData[0];
var str = arrData[0];
var n = str.length;
if (n>0) {
//
//var myTableDiv2 = document.getElementById("myDynamicTable2");
//var table3 = document.createElement('TABLE');
//table3.border='1';
//var tableBody3 = document.createElement('TBODY');
//table3.appendChild(tableBody3);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var lblt = document.createTextNode('Item Desc - '+arrData[0]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "100px";
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("value", '');
input.setAttribute("name", serial+'Qty');
input.setAttribute("id", serial+'Qty');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
input.setAttribute("data-parsley-type",'number');
input.onchange = setTwoNumberDecimal;
td.appendChild(lblt);
tr.appendChild(td);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
var td = document.createElement('TD');
var lblt1 = document.createTextNode('Enter Quantity - ');
td.appendChild(lblt1);
td.appendChild(input);
tr.appendChild(td);
//alert(arrData[0]);
myTableDiv2.appendChild(table1);
//var inputs = document.getElementsByName(serial+'Qty');
//for (var i = 0; i < inputs.length; i++) {
// if (inputs[i].name = serial+'Qty') {
// alert(inputs[1].name);
//inputs[i].focus();
//break;
// }
//
//}
var inputs2 = document.getElementById(serial+'Qty');
inputs2.focus();
inputs2.focus();
//inputs2.focus();
serial++;
} else {
}
//var allTags = document.body.getElementsByTagName('*');
//var ids = [];
//for (var tg = 0; tg< allTags.length; tg++) {
// var tag = allTags[tg];
// if (tag.id) {
// ids.push(tag.id);
// }
//}
//alert(ids);
//var oformo = document.forms["1ItemCode");
//alert (oForm0);
//var valdesc = document.getElementById("");
}
function SetValues(sRawData)
{
//window.location.reload();
var arrData = sRawData.split("|");
var oForm = document.forms["GetData"];
//$('myDynamicTable2, table1').remove();
$('#myDynamicTable2').closest('tr').remove();
document.getElementById("myDynamicTable").innerHTML = "";
document.getElementById("myDynamicTable1").innerHTML = "";
document.getElementById("myDynamicTable2").innerHTML = "";
document.getElementById("myDynamicTable3").innerHTML = "";
//document.getElementById("myDynamicTable2").innerHTML = "<br>";
//document.getElementById("table1").innerHTML = "";
serial=1;
var myTableDiv = document.getElementById("myDynamicTable");
var p=1;
var u=0;
u=parseInt(arrData[0]);
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i=0; i<u; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "80px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "120px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "50px";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
for (var j=0; j<1; j++) {
var lblt = document.createTextNode(arrData[p]);
var td = document.createElement('TD');
td.style.fontSize = '12px';
td.style.fontWeight = 'bold';
td.style.width = "70px";
td.style.wordWrap = "break-word";
td.appendChild(lblt);
tr.appendChild(td);
p++;
}
var tr = document.createElement('TR');
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table);
var myTableDiv1 = document.getElementById("myDynamicTable1");
var table = document.createElement('TABLE');
table.border='1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var j=0; j<1; j++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Press F7 to Add');
btn.appendChild(btnt);
btn.title = "Press F7 to Add";
btn.value = arrData[p];
var bin=1;
//----------shortcut.add("F7", function() {
hotkeys('f7', function(event, handler){
// Prevent the default refresh event under WINDOWS system
event.preventDefault()
// alert(serial+"BinLocation");
myTableDiv2 = document.getElementById("myDynamicTable2");
table1 = document.createElement('TABLE');
table1.border='1';
tableBody1 = document.createElement('TBODY');
table1.appendChild(tableBody1);
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
for (var j=0; j<1; j++) {
var input = document.createElement('input');
input.type = "text";
input.setAttribute("size",'15');
input.setAttribute("autofocus",'True');
input.setAttribute("value", '');
input.setAttribute("name", serial+'BinLocation');
input.setAttribute("id", serial+'BinLocation');
input.setAttribute("required",'true');
input.setAttribute("data-parsley-required",'true');
//input.required = required;
input.onkeydown = function(){ValueChangedDesc(this);};
var btn = document.createElement('hyper');
var btnt = document.createTextNode('Delete');
btn.appendChild(btnt);
btn.title = "Delete";
//shortcut.add("f4", function() {deleteRow(this) });
btn.onclick = function() {deleteRow(this)};
var lblt = document.createTextNode('Bin Location - ');
var td = document.createElement('TD');
td.appendChild(lblt);
td.appendChild(input);
tr.appendChild(td);
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
bin++;
}
var tr = document.createElement('TR');
tableBody1.appendChild(tr);
myTableDiv2.appendChild(table1);
var inputs = document.getElementById(serial+'BinLocation');
inputs.focus();
inputs.focus();
serial++;
});
var td = document.createElement('TD');
td.appendChild(btn);
tr.appendChild(td);
myTableDiv1.appendChild(table);
}
}
function validateForm() {
var x = document.forms["myForm"]["Request"].value;
var e = document.forms["myForm"];
e=e.getElementsByTagName('input');
e=(e.length)+1;
if (x == null || x == "") {
alert("Select GRN");
return false;
}
if (e==2) {
alert("2Number of fields is invalid");
return false;
}
//alert(e) ; // 6
if ((e - 2) % 3 !== 0) {
alert("Number of fields is invalid");
return false;
}
}
I expect that without refreshing, any number of times the user selects the order and presses 'f7', the bin location fields should not duplicate.
Thanks in advance.

How to delete row in table?

I want delete row which I created in function add(). When I use function deleteRow() row will be deleted but I can't use my add() function again. Someone knows why?
var trIdP =0;
function add() {
var typeP = document.getElementById("typeP").value;
var valueP = document.getElementById("valueP").value;
var newText = document.createTextNode(typeP);
var newText2 = document.createTextNode(valueP+" Eur");
var newText3 = document.createTextNode("button");
var tablePr = document.getElementById("tableP").getElementsByTagName('tbody')[0];
if ((typeP != "") && (valueP != "")) {
var newRow = tablePr.insertRow(trIdP);
newRow.id = ("trP"+trIdP);
var newCell1 = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
newCell1.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.innerHTML = "<a onclick=\"deleteRow("+trIdP+")\"><img src=\"x.gif\" alt=\"Delete row\"></a>";
document.getElementById("typeP").value = "";
document.getElementById("valueP").value = "";
trIdP++;
}
}
function deleteRow(id){
document.getElementById("trP"+id).remove();
}
You're forgetting to decrease the trIdP counter.
Update:
// Code goes here
var trIdP = 0;
function add() {
var typeP = document.getElementById("typeP").value;
var valueP = document.getElementById("valueP").value;
var newText = document.createTextNode(typeP);
var newText2 = document.createTextNode(valueP + " Eur");
var newText3 = document.createTextNode("button");
var tablePr = document.getElementById("tableP").getElementsByTagName('tbody')[0];
if ((typeP !== "") && (valueP !== "")) {
var newRow = tablePr.insertRow(-1);
newRow.id = "trP" + trIdP;
var newCell1 = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
newCell1.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.innerHTML = "<a onclick=\"deleteRow(" + trIdP + ")\"><div>Row: " + trIdP + "</div></a>";
document.getElementById("typeP").value = "";
document.getElementById("valueP").value = "";
trIdP++;
}
}
function deleteRow(id) {
document.getElementById("trP" + id).remove();
}
Check out this plunker

dynamically added input text field and get values to php and send to mysql

I have created like attachment and I have some problem to develop. The text boxes in bottom are dynamically created when add Article button pressed and now I want to update that "Added Article Details" section insert into mysql database some times have 5 rows sometime 2 rows and 1 row also wants to add. I named text box 1,2,3,4,5,6....... how to solve
My Javascript
function added_artic() {
if (added_art) {
document.getElementById('added_article').style.cssText = "display:block;";
var art_name = document.getElementsByName('article_name')[0].value;
var app = document.getElementsByName('appearance')[0].value;
var weight = document.getElementsByName('weight')[0].value;
var netWeight = document.getElementsByName('net_weight')[0].value;
var qty = document.getElementsByName('qty')[0].value;
var test = document.getElementsByName('test')[0].selectedOptions[0].text;
var added = document.getElementById("added");
var i_artname = document.createElement('input');
i_artname.value = art_name;
i_artname.name = "art_name" + art_name_id++;
i_artname.id = "txt_added";
i_artname.disabled = true;
added.appendChild(i_artname);
var i_app = document.createElement('input');
i_app.value = app;
i_app.name = "app" + app_id++;
i_app.id = "txt_added";
i_app.disabled = true;
added.appendChild(i_app);
var i_weight = document.createElement('input');
i_weight.value = weight;
i_weight.name = "weight" + weight_id++;
i_weight.id = "txt_added";
i_weight.className = "cal_weight";
i_weight.disabled = true;
added.appendChild(i_weight);
var i_netweight = document.createElement('input');
i_netweight.value = netWeight;
i_netweight.name = "netWeight" + netWeight_id++;
i_netweight.id = "txt_added";
i_netweight.className = "cal_netWeight";
i_netweight.disabled = true;
added.appendChild(i_netweight);
var i_qty = document.createElement('input');
i_qty.value = qty;
i_qty.name = "qty" + qty_id++;
i_qty.id = "txt_added";
i_qty.className = "cal_qty";
i_qty.disabled = true;
added.appendChild(i_qty);
var i_test = document.createElement('input');
i_test.value = test;
i_test.name = "test" + test_id++;
i_test.id = "txt_added";
i_test.className = "cal_test";
i_test.disabled = true;
added.appendChild(i_test);
var remove_btn = document.createElement('input');
remove_btn.type = "button";
remove_btn.value = "";
remove_btn.id = "remove_btn";
remove_btn.onclick = function ()
{
i_artname.parentElement.removeChild(i_artname);
i_app.parentElement.removeChild(i_app);
i_weight.parentElement.removeChild(i_weight);
i_netweight.parentElement.removeChild(i_netweight);
i_qty.parentElement.removeChild(i_qty);
i_test.parentElement.removeChild(i_test);
edit_btn.parentElement.removeChild(edit_btn);
this.parentElement.removeChild(this);
get_total();
if (!document.getElementsByName("test1")[0] && !document.getElementsByName("test2")[0] && !document.getElementsByName("test3")[0] && !document.getElementsByName("test4")[0] && !document.getElementsByName("test5")[0] && !document.getElementsByName("test6")[0] && !document.getElementsByName("test7")[0] && !document.getElementsByName("test8")[0] && !document.getElementsByName("test9")[0] && !document.getElementsByName("test10")[0])
{
document.getElementById('added_article').style.cssText = "display:none;";
}
}
added.appendChild(remove_btn);
var edit_btn = document.createElement('input');
edit_btn.type = "button";
edit_btn.value = "";
edit_btn.id = "edit_btn";
var a = 'weight' + (weight_id - 1);
var b = 'netWeight' + (netWeight_id - 1);
var c = 'qty' + (qty_id - 1);
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = false;
document.getElementsByName(b)[0].disabled = false;
document.getElementsByName(c)[0].disabled = false;
edit_btn.style.cssText = "background-image: url('images/update.png');";
edit_btn.onclick = function ()
{
document.getElementsByName(a)[0].disabled = true;
document.getElementsByName(b)[0].disabled = true;
document.getElementsByName(c)[0].disabled = true;
edit_btn.style.cssText = "background-image: url('images/edit.png');";
get_total();
};
};
added.appendChild(edit_btn);
document.getElementsByName('article_name')[0].value = "Article Name";
document.getElementsByName('appearance')[0].value = "Appearance";
document.getElementsByName('weight')[0].value = "";
document.getElementsByName('net_weight')[0].value = "";
document.getElementsByName('qty')[0].value = "";
document.getElementsByName('test')[0].value = "Select You Tested Karatage type";
}
}
my Project screen shot -

Update javascript table: Uncaught TypeError: Object [object Object] has no method 'tableRow'

I'm making a contacts app that updates a table with the users input but can't seem to get the table to update once I input data I only get the error above. Not sure how what I've to change the method to, I've tried lots of different functions etc., but no luck.
var nameField, addressField, emailField, postcodeField;
function twoDigit(v){
if(v.toString().length < 2){
return "0"+v.toString();
} else {
return v.toString();
}
}
var Contact = function(name, address, email, postcode){
this.name = name;
this.address = address;
this.email = email;
this.postcode = postcode;
this.completed = false;
};
var contacts = [];
Contact.prototype.toString = function(){
var s = this.name + '\n' + this.address + '\n' + this.email + + '/n'
+ this.postcode.toString() + '\n';
if(this.completed){
s += "Completed\n\n";
} else {
s += "Not Completed\n\n";
}
return s;
};
var addContact = function(nameField, addressField, emailField, postcodeField){
a = new Contact(nameField.value, addressField.value,
emailField.value, postcodeField.value);
contacts.push(a);
};
var clearUI = function(){
var white = "#fff";
nameField.value = "";
nameField.style.backgroundColor = white;
addressField.value = "";
addressField.style.backgroundColor = white;
emailField.value = "";
emailField.style.backgroundColor = white;
postcodeField.value = "";
postcodeField.style.backgroundColor = white;
};
var updateList = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th>
<th>Address</th><th>Email</th><th>Postcode</th><th>Completed</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};
var add = function(){
addContact(nameField, addressField, emailField, postcodeField);
clearUI();
updateList();
};
var cancel = function(){
clearUI();
updateList();
};
window.onload = function(){
nameField = document.getElementById("name");
addressField = document.getElementById("address");
emailField = document.getElementById("email");
postcodeField = document.getElementById("postcode");
okButton = document.getElementById("ok");
okButton.onclick = add;
cancelButton = document.getElementById("cancel");
cancelButton.onclick = cancel;
clearUI();
};
var showTable = function(){
var tableDiv = document.getElementById("table"),
table = "<table border='1'><thead><th>Name</th>
<th>Address</th><th>Email</th> <th>Postcode</th></thead>";
for(var i=0, j=contacts.length; i<j; i++){
var contacts1 = contacts[i];
table += contacts1.tableRow();
}
table+="</table>";
tableDiv.innerHTML = table;
};

Categories

Resources