Supose I have a function that calls the same function twice, with differents parameter each time, some like this:
function one(){
two(a,b);
two(c,d);
}
When I call function one, only the first function two is executed, but not the second one. Is there a way to do this in Javascript only? (not Jquery)
Here's the code in cuestion (is a little text-based RPG)
window.onload = init;
function init(){
document.onmousedown = function disableselect(e) {return false;};
/*ELEMENTS*/
var monsterPicture = document.createElement('div');
monsterPicture.setAttribute('class', 'monsterPicture');
monsterPicture.style.position = 'absolute';
monsterPicture.style.top = '0';
monsterPicture.style.right = '0';
monsterPicture.style.bottom = '0';
monsterPicture.style.left = '0';
monsterPicture.style.height = '350px';
monsterPicture.style.width = '350px';
monsterPicture.style.margin = 'auto';
monsterPicture.style.backgroundColor = 'grey';
document.body.appendChild(monsterPicture);
var textInfo = document.createElement('textarea');
textInfo.setAttribute('class', 'textInfo');
textInfo.style.position = 'absolute';
textInfo.style.top = '0';
textInfo.style.bottom = '0';
textInfo.style.right = '0';
textInfo.style.height = '350px';
textInfo.style.width = '250px';
textInfo.style.margin = 'auto 50px auto auto';
textInfo.style.backgroundColor = 'white';
textInfo.style.overflowY = 'hidden';
textInfo.style.resize = 'none';
textInfo.readOnly = 'true';
textInfo.disabled = 'true';
textInfo.style.cursor = "default";
document.body.appendChild(textInfo);
var statsArea = document.createElement('div');
statsArea.setAttribute('class', 'statsArea');
statsArea.style.position = 'absolute';
statsArea.style.top = '0';
statsArea.style.top = '0';
statsArea.style.bottom = '0';
statsArea.style.right = '0';
statsArea.style.height = '350px';
statsArea.style.width = '200px';
statsArea.style.margin = 'auto 700px auto auto';
document.body.appendChild(statsArea);
var heroInfo = document.createElement('textarea');
heroInfo.setAttribute('class', 'heroInfo');
heroInfo.style.height = '160px';
heroInfo.style.width = '200px';
heroInfo.style.marginTop = '10px';
heroInfo.style.backgroundColor = 'white';
heroInfo.style.overflowY = 'hidden';
heroInfo.style.resize = 'none';
heroInfo.readOnly = 'true';
heroInfo.disabled = 'true';
heroInfo.style.cursor = "default";
document.body.appendChild(heroInfo);
var monsterInfo = document.createElement('textarea');
monsterInfo.setAttribute('class', 'monsterInfo');
monsterInfo.style.height = '160px';
monsterInfo.style.width = '200px';
monsterInfo.style.backgroundColor = 'white';
monsterInfo.style.overflowY = 'hidden';
monsterInfo.style.resize = 'none';
monsterInfo.readOnly = 'true';
monsterInfo.disabled = 'true';
monsterInfo.style.cursor = "default";
document.body.appendChild(monsterInfo);
statsArea.appendChild(monsterInfo);
statsArea.appendChild(heroInfo);
/*CONSTRUCTOR FUNCTIONS*/
function character (name, hitpoints, armorclass, attackbonus, weapondamage) {
this.name = name;
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
this.stats = function(){
return this.name + "\n" +
"Hit Points: " + this.hitPoints + "\n" +
"Armor Class: " + this.armorClass + "\n" +
"Attack Bonus: " + this.attackBonus + "\n" +
"Weapon Damage: " + this.weaponDamage;
};
this.alive = true;
this.reset = function (){
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
};
}
var Arquer = new character("Arquer", 15, 6, 5, 8);
function selectMonster () {
var werewolf = new character("Werewolf", 15, 4, 4, 3);
var goblin = new character("Goblin", 15, 4, 4, 3);
switch(Math.floor(Math.random()*2)+1){
case 1: return werewolf;
case 2: return goblin;
}
}
var buttonAttack= document.createElement('input');
buttonAttack.setAttribute('type','button');
buttonAttack.setAttribute('value','Attack');
document.body.appendChild(buttonAttack);
var current_monster = selectMonster();
heroInfo.value = Arquer.stats() + "\n" + "Alive: " + Arquer.alive;
monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
function attack (attacker, defender, attackerInfo, defenderInfo){
var d20 = Math.floor(Math.random()*20)+1;
var d_wp = Math.floor(Math.random()*attacker.weaponDamage)+1;
/*ROUND ONE*/
if (d20+attacker.attackBonus>defender.armorClass){
textInfo.value += attacker.name +" d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass + "\n" + attacker.name +" hits! d" + attacker.weaponDamage + ": " + d_wp + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
defender.hitPoints = defender.hitPoints - d_wp;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}
else {
textInfo.value += attacker.name + " misses! d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass;
textInfo.scrollTop = textInfo.scrollHeight;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}}
function check_defeat (attacker, defender, attackerInfo, defenderInfo) {
if (attacker.hitPoints <= 0){
attacker.hitPoints = 0;
attacker.alive = false,
attackerInfo.value = attacker.stats();
attackerInfo.append("\n" + "Alive: " + attacker.alive);
textInfo.value += "\n" +defender.name + " killed " + attacker.name + "!";
textInfo.scrollTop = textInfo.scrollHeight;
}
if (defender.hitPoints <= 0){
defender.hitPoints = 0;
defender.alive = false,
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
textInfo.value += "\n" + attacker.name + " killed " + defender.name + "!";
}
}
function reset (hero, monster) {
if (hero.alive===false){
hero.reset();
hero.alive = true;
heroInfo.value = hero.stats();
heroInfo.append("\n" + "Alive: " + hero.alive);
}
if (monster.alive===false){
monster.reset();
monster.alive = true;
monsterInfo.value = monster.stats();
monsterInfo.append("\n" + "Alive: " + monster.alive);
}
}
}
(For some reason it doesn't work in jsfiddle). The problem is in the function battle.
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
When I call it, it just execute the first function attack, but not the second one.
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
When executing a function you don't have to write function up front.
try
function one(){
two(a,b);
two(c,d);
}
It should work -
function two(a,b){
console.log(a+b);
}
function one(){
two(1,2);
two(3,4);
}
one();
output:
2
7
the first function two is executed
This is highly unlikely; why do you believe it was executed? Before you call anything, or anything is executed, there is a syntax error, probably something like "Unexpected token ;", because the syntax
function two(a, b);
is invalid; function definitions must have a body in curly braces. You would see the error if you looked at the console; did you? It must be:
function two(a, b) { }
But apparently you just want to call the function, in which case you should use the basic function call syntax of two(a, b). function is for defining functions, not calling them.
Best and easiest solution is to use Promist.all() with nodejs
Example
let _ = require('underscore')
let response = ['some data','other data']
return Promise.all(_.map(response, function (data) { return
functionName(data) }))
.then((response)=>{
console.log(response)
})
Result
['response1','response2']
you can simply call a function twice or any time you want just remember its arguments and its data types since you are not forced to put data type on function call but if there is wrong data type it can create serious mess.
//currently in a mess
Related
I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.
working on some word problems for my intro class and my html keeps getting stuck in a loop in the alert section of my code. once it goes in there it doesn't come back out no matter if I am inputting correctly. this is a beginner class so we have only just gotten into loops and switches so please keep it basic. thanks in advance!
var custOwed, numCust, dayTotal;
var woodTotal, alumTotal, steelTotal;
var rate;
var woodCount = 0;
var alumCount = 0;
var steelCount = 0;
var woodAccum = 0;
var alumAccum = 0;
var steelAccum = 0;
var anotherOrder = "yes";
var woodRate = 10;
var alumRate = 15;
var steelRate = 25;
var errorFlag = 0;
anotherOrder = prompt("Another Order", "yes or no");
while (anotherOrder == "yes") {
poleType = prompt("What type of pole would you like today?", "wood, aluminum, or steel");
numFeet = prompt("How many feet?", "10");
numFeet = parseInt(numFeet);
switch (poleType) {
case "wood":
woodCount = woodCount + 1;
woodAccum = woodAccum + numFeet;
rate = woodRate;
break;
case "aluminum":
alumCount = alumCount + 1;
alumAccum = alumAccum + numFeet;
rate = alumRate;
break;
case "steel":
steelCount = steelCount + 1;
steelAccum = steelAccum + numFeet;
rate = steelRate;
break;
default:
errorFlag = 1;
break;
}
if (errorFlag == 1) {
alert("You typed " + poleType + " the only choices were wood, aluminum, or steel");
anotherOrder = "yes";
} else {
custOwed = numFeet * rate;
alert("You Owe" + custOwed);
anotherOrder = prompt("Another Customer?", "yes or no");
}
}
numCust = woodCount + alumCount + steelCount;
woodTotal = woodAccum * woodRate;
alumTotal = alumAccum * alumRate
steelTotal = steelAccum * steelRate
dayTotal = woodTotal + alumTotal + steelTotal;
document.write("Number of Customers: " + numCust);
document.write("<br>Wood Customers: " + woodCount);
document.write("<br>Total Feet of Wood: " + woodAccum);
document.write("<br>Total owed of Wood: $" + woodTotal.toFixed(2));
document.write("<br>Aluminum Customers: " + alumCount);
document.write("<br>Total Feet of Aluminum: " + alumAccum);
document.write("<br>Total owed of Aluminum: $" + alumTotal.toFixed(2));
document.write("<br>Steel Customers: " + alumCount);
document.write("<br>Total Feet of Steel: " + alumAccum);
document.write("<br>Total owed of Steel: $" + alumTotal.toFixed(2));
document.write("<br>Total owed from the day: $" + dayTotal.toFixed(2));
I have the following code.
is this.payment another property of the car object?
when i want to calculate the price of a car, for example:
var work_car_payments= work_car.payment();
why should i use .payment()?
payment hasn't been defined as a function in the code. I'm a little confused.
function get_payment() {
var the_payment = 250;
the_payment += (this.seats == "leather") ? 100 : 50;
the_payment += (this.engine == "V-8") ? 150 : 75;
the_payment += (this.theradio == "CD Player") ? 35 : 10;
return the_payment;
}
function car(seats, engine, theradio) {
this.seats = seats;
this.engine = engine;
this.theradio = theradio;
this.payment = get_payment;
}
var work_car = new car("cloth", "V-6", "Tape Deck");
var fun_car = new car("leather", "V-8", "CD Player");
var custom_car = new car(fun_car.seats, work_car.engine, fun_car.theradio);
var work_car_payment = work_car.payment();
var fun_car_payment = fun_car.payment();
var custom_car_payment = custom_car.payment();
document.write("<h2>The information on the cars you requested:</h2>");
document.write("<strong>Work Car: </strong>");
document.write(work_car.seats + "," + work_car.engine + "," + work_car.theradio);
document.write("<br />");
document.write("<strong>Payments:</strong> $" + work_car_payment);
document.write("<p>");
document.write("<strong >Fun Car: </strong>");
document.write(fun_car.seats + "," + fun_car.engine + "," + fun_car.theradio);
document.write("<br />");
document.write("<strong>Payments:</strong> $" + fun_car_payment);
document.write("</p>");
document.write("<p>");
document.write("<strong>Custom Car: </strong>");
document.write(custom_car.seats + "," + custom_car.engine + ",");
document.write(custom_car.theradio);
document.write("<br />");
document.write("<strong>Payments:</strong> $" + custom_car_payment);
document.write("</p>");
get_payment is defined as a function.
The car() function contains:
this.payment = get_payment;
This defines the payment property as containing that function.
Note that the more common way to do this would be to assign the property in the car prototype, rather than assigning it to each object, since all cars get the same function.
function get_payment() {
var the_payment = 250;
the_payment += (this.seats == "leather") ? 100 : 50;
the_payment += (this.engine == "V-8") ? 150 : 75;
the_payment += (this.theradio == "CD Player") ? 35 : 10;
return the_payment;
}
function car(seats, engine, theradio) {
this.seats = seats;
this.engine = engine;
this.theradio = theradio;
}
car.prototype.payment = get_payment;
I have a problem with my code, i wanna see my passed 4 generated number (Math.random), on a history box, but these numbers show out the same. Is there a way to delay a var?
I have tried putting var in order, but this makes no delay.
my html:
<div class="text-position-history">
<div class="text-style-history">
<p id="historyT"></p>
</div>
</div>
</body>
</html>
My javascript:
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var history1 = result;
var history2 = history1;
var history3 = history2;
document.getElementById('historyT').innerHTML = "Guessed number: " + " " + result + " " + history1 + " " + history2 + " " + history3;
}
Is there a way to do this?
Why don't you just create an array and then append the new values of result to the array after you call Math.random()?
var resultHistory = new Array();
var result = Math.random();
resultHistory.push(result);
Then print out the array later on.
Why not just use array of numbers?
var _history = [];
function toHTMLElement(historyNode)
{
var node = document.createElement("div");
node.innerHTML = historyNode.text;
node.style.background = historyNode.win?'green':'red';
return node;
}
function renderHistory()
{
var result = document.getElementById("result");
result.innerHTML = "";
_history.forEach(function(e){
result.appendChild(toHTMLElement(e));
});
}
document.getElementById("form").addEventListener("submit", function(e){
e.preventDefault();
_history.push((Math.random()>0.5)?{win: true, text: 'You win'}:{win: false, text: 'You lose'});
if (_history.length > 3) _history.shift();
renderHistory();
});
<form id="form">
<input type="submit">
</form>
<div id="result"></div>
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var myList = [result, result, result];
var history1 = myList.shift();
var history2 = myList.shift();
var history3 = myList.shift();
document.getElementById('historyT').innerHTML = "Guessed numbesr: " + " " + history1 + " " + history2 + " " + history3;
}
This still gives the same result?
I think actually changing the order of your history vars should fix it.
Change them to
var history3 = history2;
var history2 = history1;
var history1 = result;
Right now you are overwritung everything to results because:
var history1 = result
var history2 = history1 (history1 is already referring to result by now)
This question already exists:
Update javascript table: Uncaught TypeError: Object [object Object] has no method 'tableRow'
Closed 9 years ago.
I'm creating a contacts book and wanting a table to update as the user inputs the data, but I keep getting this error about 'tableRow'. I've tried changing it to different function names etc. but can't seem to find the solutions.
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;
};
Contact.prototype.tableRow = function(){
var tr = "<tr><td>" + this.name + "</td><td>" +
this.address + "</td><td>" + this.email +
"</td><td>" + this.address + ">";
};
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;
};
Add a tableRow function to Contact
Contact.prototype.tableRow = function() {
return '<tr>' + '<td>' + this.name + '</td>' + '<td>' + this.address + '</td>' + '<td>' + this.email + '</td>' + '<td>' + this.postcode + '</td>' + '</tr>';
}