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

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.

Related

How to proper target JSON response when using append

I cannot seem to get the syntax right when targeting JSON response.
In my project I have a <div id="percentage"></div>.
I want to append the score as text to the div but i'm getting "Cannot read property 'categories' of undefined" error in the console.
I think it is a syntax error from my side.
How to fix it?
JSON:
{"lighthouseResult":{"categories":{"performance":{"score":1.0},"accessibility":{"score":0.9},"best-practices":{"score":0.92},"seo":{"score":0.8},"pwa":{"score":0.54}}}}
Javascript:
function loadAnalysis() {
var xhttp = new XMLHttpRequest();
var url = document.getElementById("url").value;
if (url == "") {
alert("Please enter URL");
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
var table = document.createElement('table');
table.setAttribute('class', 'result');
var properties = ['performance', 'accessibility', 'best-practices', 'seo', 'pwa'];
var capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.classList.add("category");
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
console.log("jsonResponse", jsonResponse);
var categories = Object.keys(jsonResponse["lighthouseResult"]);
for (var r = 0; r < categories.length; r++) {
tr = document.createElement('tr');
row = jsonResponse["lighthouseResult"][categories[r]];
var ids = 'performance,accessibility,best-practices,seo,pwa'.split(',');
for (var i = 0; i < properties.length; i++) {
    var td = document.createElement('td');
    td.id = ids[i];
td.className = "score";
td.appendChild(document.createTextNode(row[properties[i]].score));
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('analysisTable').appendChild(table);
}
};
xhttp.open("GET", "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + encodeURIComponent(url) +
"&fields=lighthouseResult%2Fcategories%2F*%2Fscore&prettyPrint=false&strategy=desktop&category=performance&category=pwa&category=best-practices&category=accessibility&category=seo&key=AIzaSyDSNxhf0capOwppqlg9wZJUvzBewxf6mHU", true);
xhttp.send();
}
Part where I'm struggling with:
var seldiv = document.getElementById("percentage");
seldiv.append(data.lighthouseResult.categories.performance.score);
I think you are after jsonResponse.lighthouseResult.categories.performance.score. You perform var jsonResponse = JSON.parse(data); so data is essentially text, and the JSON representation of that text is jsonResponse

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

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

what is error in this js code

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

Asynchronous execution of javascript code

I am studying javascript and json but I've some problems: I have a script that works with json but the performances of what I wrote aren't that good. The code works only if I do a debug step by step with firebug or other tools and that makes me think that the execution of the code (or a part of it ... the one that creates the table as you'll see) requires too much time so the browser stops it.
The code is:
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function() {
if(richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
for(i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function() {
if(richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for(j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for(u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for(c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
The problem is that the code that should make the table doesn't wait for the complete execution of the code that works with the json files. How can I fix it? I would prefer,if possible, to solve that problem with something easy, without jquery and callbacks (I am a beginner).
You'll have to move som code around to make that work. at first, split it up in some functions, then it is easier to work with. I dont know if it works, but the idea is that first it loads the arrayEntita. When that is done, it fills the other 2 arrays. And when the last array has been filled, it builds the table.
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function () {
if (richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
BuildArrayEntita();
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
}
function BuildArrayEntita() {
for (i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function () {
if (richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for (j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
//If it is the last call to populate arraycardbyuser, build the table:
if (i + 1 == arrayEntita.length)
BuildTable();
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
}
function BuildTable() {
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for (u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for (c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
i dont know if this check:
if (i + 1 == arrayEntita.length)
BuildTable();
but else you have to check if alle responseses have returned before executing buildtable();
AJAX requests are asynchronous. They arrive at an unknown period during execution and JavaScript does not wait for the server to reply before proceeding. There is synchronous XHR but it's not for ideal use. You'd lose the whole idea of AJAX if you do so.
What is usually done is to pass in a "callback" - a function that is executed sometime later, depending on when you want it executed. In your case, you want the table to be generated after you receive the data:
function getData(callback){
//AJAX setup
var richiestaEntity = new XMLHttpRequest();
//listen for readystatechange
richiestaEntity.onreadystatechange = function() {
//listen for state 4 and ok status (200)
if (richiestaEntity.readyState === 4 && richiestaEntity.status === 200) {
//execute callback when data is received passing it
//what "this" is in the callback function, as well as
//the returned data
callback.call(this,richiestaEntity.responseText);
}
}
richiestaEntity.open("GET", "danielericerca.json"); //third parameter defaults to true
richiestaEntity.send();
}
function displayArrayCards() {
//this function passed to getData will be executed
//when data arrives
getData(function(returnedData){
//put here what you want to execute when getData receives the data
//"returnedData" variable inside this function is the JSON returned
});
}
As soon as you have made the ajax call, put all of the rest of the code inside the readystatechange function. This way, it will execute everything in order.
Edit: #Dappergoat has explained it better than I can.

Categories

Resources