nested object is not inserted into table using javascript - javascript
I am new to javaScript
here in this code, I'm trying to add companyDetails(nested object of productDetails) in the table by its id.
Like, for id 1 I want to add companyDetails then in the input field of id enter id 1 and insert details in the given input fields
so my problem is that companyDetails(date,address,companyName)is not displayed in the table after adding its value for entered id
let productDetails = [
{
id: "1",
partNo: "10",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
},
{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
},
{
id: "4",
partNo: "20",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
},
{
id: "3",
partNo: "40",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}, {
id: "5",
partNo: "35",
productName: "notebook",
size: "30",
color: ["Blue", "Red", "Orange"],
description: "Writing",
}
]
/** * function to add company details */
function addCompanyDetails() {
let data = (document.getElementById('productId').value);
let date1 = document.getElementById('date').value;
let Caddress = document.getElementById('address').value;
let Cname = (document.getElementById('companyName').value);
if (data === '') {
message("enter id for search");
}
for (let i = 0; i < productDetails.length; i++) {
let companyDetails = productDetails[i].companyDetails ? productDetails[i].companyDetails : { date: "", address: "", companyName: "" };
let p = companyDetails;
if ((productDetails[i].id) == (data)) {
p.companyName = Cname ;
p.date = date1 ;
p.address = Caddress;
console.log(p.companyName);
console.log(p.date);
console.log(p.address);
}
displayData();
clearInputData();
}
}
/** * this function display the data in table */
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray, clearInputData);
}
/** * this function is for get the value from form */
function getValue() {
let id = document.getElementById('productId').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return { id, date, address, companyName };
}
/** * Function is to display the data in table */
function display(productStore, callBack) {
messageTable(" ");
let data = productDetails;
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>weight</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (let i = 0; i < data.length; i++) {
if (data[i].productWeight === undefined) {
data[i].productWeight = " ";
} else { }
if (data[i].date === undefined) {
data[i].date = " ";
} else { }
if (data[i].address === undefined) {
data[i].address = " ";
} else { }
let companyDetails = data[i].companyDetails ? data[i].companyDetails : { date: "", address: "", companyName: "" };
table += "<tr><td>" + data[i].id + "</td>";
table += "<td>" + data[i].partNo + "</td>";
table += "<td>" + data[i].productName + "</td>";
table += "<td>" + data[i].size + "</td>";
table += "<td>" + data[i].color + "</td>";
table += "<td>" + data[i].description + "</td>";
table += "<td>" + data[i].productWeight + "</td>";
table += "<td>" + companyDetails.date + "</td>";
table += "<td>" + companyDetails.address + "</td>";
table += "<td>" + companyDetails.companyName + "</td>";
}
messageTable(table);
clearInputData();
}
/** * function is to print the table */
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
/** * this function is to clear the data */
function clearInputData() {
document.getElementById("productId").value = "";
document.getElementById("address").value = "";
document.getElementById("date").value = "";
document.getElementById("companyName").value = "";
}
<!DOCTYPE html>
<html>
<head>
<script src="add.js"></script>
<style>
th,
td,
p,
input {
font-family: Arial, Helvetica, sans-serif;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 10px 10px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body onload="display()">
<h2>Product Details:</h2>
<form action="">
<label for="id">Id: </label> <input type="number" id="productId" required> <input type="button"
value="autofill" onclick="auto()"><br><br>
<label for="EstablishDate">Establish Date:</label> <input type="date" id="date" required><br><br>
<label for="address">Address:</label><br><br> <textarea name="address" id="address" cols="30"
rows="10"></textarea><br><br>
<label for="CompanyName">Company Name:</label> <input type="text" id="companyName" required><br><br>
<input type="button" value="add company details" onclick="addCompanyDetails()"><br><br>
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
</form>
</body>
</html>
Here I am adding the Information of company with Specific ID to its respectice Product id
like productDetails[i].address = Caddress; in addCompanyDetails() function and then
in display function I have replaced companyDetails.address to data[i].address .
But be sure it will lose its data when you reload the page .
let productDetails = [
{
id: "1",
partNo: "10",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
},
{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
},
{
id: "4",
partNo: "20",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
},
{
id: "3",
partNo: "40",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}, {
id: "5",
partNo: "35",
productName: "notebook",
size: "30",
color: ["Blue", "Red", "Orange"],
description: "Writing",
}
]
/** * function to add company details */
function addCompanyDetails() {
let data = (document.getElementById('productId').value);
let date1 = document.getElementById('date').value;
let Caddress = document.getElementById('address').value;
let Cname = (document.getElementById('companyName').value);
if (data === '') {
message("enter id for search");
}
for (let i = 0; i < productDetails.length; i++) {
let companyDetails = productDetails[i].companyDetails ? productDetails[i].companyDetails : { date: "", address: "", companyName: "" };
let p = companyDetails;
if ((productDetails[i].id) == (data)) {
p.companyName = Cname ;
productDetails[i].date = date1 ;
productDetails[i].address = Caddress;
productDetails[i].companyName=Cname;
}
displayData();
clearInputData();
}
}
/** * this function display the data in table */
function displayData(companyDetails) {
objectArray = Object.values(productDetails);
display(objectArray, companyDetails,clearInputData);
}
/** * this function is for get the value from form */
function getValue() {
let id = document.getElementById('productId').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return { id, date, address, companyName };
}
/** * Function is to display the data in table */
function display(productStore,callBack) {
messageTable(" ");
let data = productDetails;
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>weight</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (let i = 0; i < data.length; i++) {
if (data[i].productWeight === undefined) {
data[i].productWeight = " ";
} else { }
if (data[i].companyName === undefined) {
data[i].companyName = " ";
} else { }
if (data[i].date === undefined) {
data[i].date = " ";
} else { }
if (data[i].address === undefined) {
data[i].address = " ";
} else { }
table += "<tr><td>" + data[i].id + "</td>";
table += "<td>" + data[i].partNo + "</td>";
table += "<td>" + data[i].productName + "</td>";
table += "<td>" + data[i].size + "</td>";
table += "<td>" + data[i].color + "</td>";
table += "<td>" + data[i].description + "</td>";
table += "<td>" + data[i].productWeight + "</td>";
table += "<td>" + data[i].date + "</td>";
table += "<td>" + data[i].address + "</td>";
table += "<td>" + data[i].companyName + "</td>";
}
messageTable(table);
clearInputData();
}
/** * function is to print the table */
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
/** * this function is to clear the data */
function clearInputData() {
document.getElementById("productId").value = "";
document.getElementById("address").value = "";
document.getElementById("date").value = "";
document.getElementById("companyName").value = "";
}
<!DOCTYPE html>
<html>
<head>
<script src="home.js"></script>
<style>
th,
td,
p,
input {
font-family: Arial, Helvetica, sans-serif;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 10px 10px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body onload="display()">
<h2>Product Details:</h2>
<form action="">
<label for="id">Id: </label> <input type="number" id="productId" required> <input type="button"
value="autofill" onclick="auto()"><br><br>
<label for="EstablishDate">Establish Date:</label> <input type="date" id="date" required><br><br>
<label for="address">Address:</label><br><br> <textarea name="address" id="address" cols="30"
rows="10"></textarea><br><br>
<label for="CompanyName">Company Name:</label> <input type="text" id="companyName" required><br><br>
<input type="button" value="add company details" onclick="addCompanyDetails()"><br><br>
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
</form>
</body>
</html>
getObjById takes in an array of objects and the id you are looking for and returns the object that has your requested id in the given array
//if the id requested does not exist in the array you gave, it returns undefined
function getObjById(arr,id){return arr.filter(a=>a.id==id)[0]}
//example usage(valid/existing id)
console.log(getObjById(productDetails,"1"))
//example usage(invalid/non-existing id)
console.log(getObjById(productDetails,"99"))
//because I have == and not === 1=="1"
console.log(getObjById(productDetails,1))
<script>
//just where I have the array to save line space for the function
let productDetails = [
{
id: "1",
partNo: "10",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
},
{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
},
{
id: "4",
partNo: "20",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
},
{
id: "3",
partNo: "40",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}, {
id: "5",
partNo: "35",
productName: "notebook",
size: "30",
color: ["Blue", "Red", "Orange"],
description: "Writing",
}
]
</script>
let productDetails = [
{
id: "1",
partNo: "10",
productName: "bag",
size: "30",
color: ["Blue"],
description: "sky bags ",
},
{
id: "2",
partNo: "15",
productName: "bottle",
size: "10",
color: ["Green", "Orange"],
description: "plastic and still",
},
{
id: "4",
partNo: "20",
productName: "lunchbox",
size: "20",
color: ["Blue", "Red"],
description: "fresh food",
},
{
id: "3",
partNo: "40",
productName: "pen",
size: "10",
color: ["Red", "Blue"],
description: "gel pen ",
}, {
id: "5",
partNo: "35",
productName: "notebook",
size: "30",
color: ["Blue", "Red", "Orange"],
description: "Writing",
}
]
/** * function to add company details */
function addCompanyDetails() {
let data = (document.getElementById('productId').value);
let Name = (document.getElementById('companyName').value);
let Cdate = (document.getElementById('date').value);
let Caddress = (document.getElementById('address').value);
if (data === '') {
message("enter id for search");
}
for (let i = 0; i < productDetails.length; i++) {
if ((productDetails[i].id) == (data)) {
productDetails[i].companyDetails = {
date: "",
companyName: "",
address: ""
}
productDetails[i].companyDetails.companyName = Name;
productDetails[i].companyDetails.date = Cdate;
productDetails[i].companyDetails.address = Caddress;
console.log(productDetails[i].companyDetails.companyName);
}
displayData();
clearInputData();
}
}
/** * this function display the data in table */
function displayData() {
objectArray = Object.values(productDetails);
display(objectArray, clearInputData);
}
/** * this function is for get the value from form */
function getValue() {
let id = document.getElementById('productId').value;
let date = document.getElementById('date').value;
let address = document.getElementById('address').value;
let companyName = document.getElementById('companyName').value;
return { id, date, address, companyName };
}
/** * Function is to display the data in table */
function display(productStore, callBack) {
messageTable(" ");
let data = productDetails;
let table = "<table border = 1 cellpadding = 10 ><th colspan=7 >Product Details</th><th colspan=7 >company Details</th><tr><th>Product Id</th><th>Part No</th><th>Name</th><th>Size</th><th>Color</th><th>Description</th><th>weight</th><th>Date</th><th>Address</th><th>Company name</th></tr>";
for (let i = 0; i < data.length; i++) {
if (data[i].productWeight === undefined) {
data[i].productWeight = " ";
} else { }
if (data[i].date === undefined) {
data[i].date = " ";
} else { }
if (data[i].address === undefined) {
data[i].address = " ";
} else { }
let companyDetails = data[i].companyDetails ? data[i].companyDetails : { date: "", address: "", companyName: "" };
table += "<tr><td>" + data[i].id + "</td>";
table += "<td>" + data[i].partNo + "</td>";
table += "<td>" + data[i].productName + "</td>";
table += "<td>" + data[i].size + "</td>";
table += "<td>" + data[i].color + "</td>";
table += "<td>" + data[i].description + "</td>";
table += "<td>" + data[i].productWeight + "</td>";
table += "<td>" + companyDetails.date + "</td>";
table += "<td>" + companyDetails.address + "</td>";
table += "<td>" + companyDetails.companyName + "</td>";
}
messageTable(table);
clearInputData();
}
/** * function is to print the table */
function messageTable(data) {
document.getElementById("messageTableA").innerHTML = data;
}
/** * this function is to clear the data */
function clearInputData() {
document.getElementById("productId").value = "";
document.getElementById("address").value = "";
document.getElementById("date").value = "";
document.getElementById("companyName").value = "";
}
<!DOCTYPE html>
<html>
<head>
<script src="add.js"></script>
<style>
th,
td,
p,
input {
font-family: Arial, Helvetica, sans-serif;
}
table,
th,
td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 10px 10px;
text-align: center;
}
th {
font-weight: bold;
}
</style>
</head>
<body onload="display()">
<h2>Product Details:</h2>
<form action="">
<label for="id">Id: </label> <input type="number" id="productId" required> <input type="button"
value="autofill" onclick="auto()"><br><br>
<label for="EstablishDate">Establish Date:</label> <input type="date" id="date" required><br><br>
<label for="address">Address:</label><br><br> <textarea name="address" id="address" cols="30"
rows="10"></textarea><br><br>
<label for="CompanyName">Company Name:</label> <input type="text" id="companyName" required><br><br>
<input type="button" value="add company details" onclick="addCompanyDetails()"><br><br>
<p id="result"></p>
<p id="demo"></p>
<p id="messageTableA"></p>
</form>
</body>
</html>
now its completely working without removing nested object
Related
Uncaught ReferenceError at HTMLButtonElement.onclick
I have a code of a quiz in html and js. The quiz has 10 question and there should be buttons to move between the questions. The first question works fine but when I try to answer the second question I get this error in the console: Game.html:1 Uncaught ReferenceError: num is not defined at HTMLButtonElement.onclick (Game.html:1) What can I do to prevent this error? I tried to copy the js code to the script element in html but it didn't work. The code of the html looks like that: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Game</title> <script src="script.js"></script> <link rel="stylesheet" href="style.css"> </head> <body id="gameBody" onload="InitGame()"> <h1>Welcome to the game</h1> <h3 class="header">Your score</h3> <h3 class="text" id="score"></h3> <h5 class="header">Choose the right answer</h5> <p class="header">The question number</p> <p class="text" id="questionNumber"></p> <p class="header">The word you need to translate</p> <p id="word"></p> <div id="image"> </div> <div id="options"> </div> <p id="message"></p> <button class="myChoise" onclick="prevQuestion()">Previous</button> <button class="myChoise" onclick="nextQuestion()">Next</button> </body> </html> ``` And in script.js I have this array of objects : let food=[{ 'ID':1, 'word':'What is the national dish of Italy', 'options':[ {name : 'פסטה, פיצה, ריזוטו'}, {name : 'המבורגר'}, {name : 'מרק עוף'} ], 'img':'img/200.jpg', 'rightAnswer':'פסטה, פיצה, ריזוטו', }, { 'ID':2, 'word':'What is the national dish of the United States?', 'options':[ {name : 'המבורגר, נקנקיה בלחמניה, פאי '}, {name : 'פיצה'}, {name : 'ריזוטו'} ], 'img':'img/23.jpg', 'rightAnswer':'המבורגר, נקנקיה בלחמניה, פאי', }, { 'ID':3, 'word':'What is the national dish of Hungary?', 'options':[ {name : 'גולאש'}, {name : 'המבורגר'}, {name : 'נקנקיה בלחמניה'} ], 'img':'img/21.jpg', 'rightAnswer':'גולאש', }, { 'ID':4, 'word':'What is the national dish of Greece?', 'options':[ {name : 'מוסקה,סלט יווני'}, {name : 'גולאש'}, {name : 'המבורגר'} ], 'img':'img/222.jpg', 'rightAnswer':'סלט יווני,מוסקה', }, { 'ID':5, 'word':'What is the national dish of Belarus?', 'options':[ {name : 'לביבה'}, {name : 'קציצות בשר'}, {name : 'מרק עוף'} ], 'img':'img/444.jpg', 'rightAnswer':'לביבה', }, { 'ID':6, 'word':'What is the national dish of the United Kingdom?', 'options':[ {name : ' פיש אנד ציפס'}, {name : 'ответ'}, {name : 'название'} ], 'img':'img/20.jpg', 'rightAnswer':' פיש אנד ציפס', }, { 'ID':7, 'word':'What is China national dish?', 'options':[ {name : 'אורז'}, {name : 'קציצות בקר'}, {name : 'המבורגר'} ], 'img':'img/486.jpg', 'rightAnswer':'אורז', }, { 'ID':8, 'word':'What is the national dish of France?', 'options':[ {name : 'באגט, קרואסון, פואה גרא'}, {name : 'נקנקיה בלחמניה'}, {name : 'לביבות'} ], 'img':'img/22.jpg', 'rightAnswer':'באגט, קרואסון, פואה גרא', }, { 'ID':9, 'word':'What is the national dish of Cyprus?', 'options':[ {name : 'חלומי'}, {name : 'באגט'}, {name : 'אורז'} ], 'img':'img/24.jpg', 'rightAnswer':'חלומי', }, { 'ID':10, 'word':'What is the national dish of Mexico?', 'options':[ {name : 'טאקו, גואקמולי'}, {name : 'אורז'}, {name : 'פיש אנד ציפס'} ], 'img':'img/264.jpg', 'rightAnswer':'טאקו,גואקמולי', } ] And this functions : let score = 0; function InitGame(){ document.getElementById("questionNumber").innerHTML = food[0].ID; document.getElementById("score").innerHTML= score; document.getElementById("word").innerHTML= food[0].word; let imgSrc = food[0].img; let img = document.createElement("img"); img.src = food[0].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML = "<button class='btn' id='1' onclick='checkAnswer(food[0].ID,this)'></button> " + "<button class='btn' id='2' onclick='checkAnswer(food[0].ID,this)'></button> " + "<button class='btn' id='3' onclick='checkAnswer(food[0].ID,this)'></button>"; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[0].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[0].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[0].options[2].name; } function checkAnswer(questionNum,btn){ for(i in food) { if(food[i].ID === questionNum) { let chosed = btn.id; let answer = food[i].options[chosed-1].name; if(answer === food[i].rightAnswer) { score = score+1; document.getElementById("score").innerHTML= score; document.getElementById("message").innerHTML = "Right answer"; nextQuestion(); } else { score = score-0.5; document.getElementById("score").innerHTML= score; document.getElementById("message").innerHTML = "wrong answer, please try again"; } } } } function nextQuestion(){ let qNum = document.getElementById("questionNumber").innerHTML; let num = ++qNum; if(num === 10) { num = 0; } document.getElementById("questionNumber").innerHTML = num; document.getElementById("score").innerHTML= score; document.getElementById("word").innerHTML= food[num].word; document.getElementById("image").innerHTML=""; let imgSrc = food[num].img; let img = document.createElement("img"); img.src = food[num].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML=""; document.getElementById("options").innerHTML = "<button class='btn' id='1' onclick='checkAnswer(food[num].ID,this)'></button> " + "<button class='btn' id='2' onclick='checkAnswer(food[num].ID,this)'></button> " + "<button class='btn' id='3' onclick='checkAnswer(food[num].ID,this)'></button>"; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name; } function prevQuestion(){ let qNum = document.getElementById("questionNumber").innerHTML; let num = --qNum; if(num === -1) { num = 10; } document.getElementById("questionNumber").innerHTML = num; document.getElementById("score").innerHTML= score; document.getElementById("word").innerHTML= food[num].word; document.getElementById("image").innerHTML=""; let imgSrc = food[num].img; let img = document.createElement("img"); img.src = food[num].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML=""; document.getElementById("options").innerHTML = `<button class='btn' id='1' onclick='checkAnswer(food[num].ID,this)'></button> <button class='btn' id='2' onclick='checkAnswer(food[num].ID,this)'></button> <button class='btn' id='3' onclick='checkAnswer(food[num].ID,this)'></button>`; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name; }
the reason you are gettting num is not defined is that you are setting the inner HTML like 'checkAnswer(food[num].ID,this)' in this case number doesn't have reference to num variable in the function instead you should use 'checkAnswer(food[" + num + "].ID,this)' so that when html renderes instead of num it will render the number like this checkAnswer(food[9].ID,this) let food = [{ 'ID': 1, 'word': 'What is the national dish of Italy', 'options': [{ name: 'פסטה, פיצה, ריזוטו' }, { name: 'המבורגר' }, { name: 'מרק עוף' } ], 'img': 'img/200.jpg', 'rightAnswer': 'פסטה, פיצה, ריזוטו', }, { 'ID': 2, 'word': 'What is the national dish of the United States?', 'options': [{ name: 'המבורגר, נקנקיה בלחמניה, פאי' }, { name: 'פיצה' }, { name: 'ריזוטו' } ], 'img': 'img/23.jpg', 'rightAnswer': 'המבורגר, נקנקיה בלחמניה, פאי', }, { 'ID': 3, 'word': 'What is the national dish of Hungary?', 'options': [{ name: 'גולאש' }, { name: 'המבורגר' }, { name: 'נקנקיה בלחמניה' } ], 'img': 'img/21.jpg', 'rightAnswer': 'גולאש', }, { 'ID': 4, 'word': 'What is the national dish of Greece?', 'options': [{ name: 'מוסקה,סלט יווני' }, { name: 'גולאש' }, { name: 'המבורגר' } ], 'img': 'img/222.jpg', 'rightAnswer': 'מוסקה,סלט יווני', }, { 'ID': 5, 'word': 'What is the national dish of Belarus?', 'options': [{ name: 'לביבה' }, { name: 'קציצות בשר' }, { name: 'מרק עוף' } ], 'img': 'img/444.jpg', 'rightAnswer': 'לביבה', }, { 'ID': 6, 'word': 'What is the national dish of the United Kingdom?', 'options': [{ name: ' פיש אנד ציפס' }, { name: 'ответ' }, { name: 'название' } ], 'img': 'img/20.jpg', 'rightAnswer': ' פיש אנד ציפס', }, { 'ID': 7, 'word': 'What is China national dish?', 'options': [{ name: 'אורז' }, { name: 'קציצות בקר' }, { name: 'המבורגר' } ], 'img': 'img/486.jpg', 'rightAnswer': 'אורז', }, { 'ID': 8, 'word': 'What is the national dish of France?', 'options': [{ name: 'באגט, קרואסון, פואה גרא' }, { name: 'נקנקיה בלחמניה' }, { name: 'לביבות' } ], 'img': 'img/22.jpg', 'rightAnswer': 'באגט, קרואסון, פואה גרא', }, { 'ID': 9, 'word': 'What is the national dish of Cyprus?', 'options': [{ name: 'חלומי' }, { name: 'באגט' }, { name: 'אורז' } ], 'img': 'img/24.jpg', 'rightAnswer': 'חלומי', }, { 'ID': 10, 'word': 'What is the national dish of Mexico?', 'options': [{ name: 'טאקו,גואקמולי' }, { name: 'אורז' }, { name: 'פיש אנד ציפס' } ], 'img': 'img/264.jpg', 'rightAnswer': 'טאקו,גואקמולי', } ] let score = 0; function InitGame() { document.getElementById("questionNumber").innerHTML = food[0].ID; document.getElementById("score").innerHTML = score; document.getElementById("word").innerHTML = food[0].word; let imgSrc = food[0].img; let img = document.createElement("img"); img.src = food[0].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML = "<button class='btn' id='1' onclick='checkAnswer(food[0].ID,this)'></button> " + "<button class='btn' id='2' onclick='checkAnswer(food[0].ID,this)'></button> " + "<button class='btn' id='3' onclick='checkAnswer(food[0].ID,this)'></button>"; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[0].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[0].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[0].options[2].name; } function checkAnswer(questionNum, btn) { debugger for (i in food) { if (food[i].ID === questionNum) { let chosed = btn.id; let answer = food[i].options[chosed - 1].name; if (answer === food[i].rightAnswer) { score = score + 1; document.getElementById("score").innerHTML = score; document.getElementById("message").innerHTML = "Right answer"; nextQuestion(); } else { score = score - 0.5; document.getElementById("score").innerHTML = score; document.getElementById("message").innerHTML = "wrong answer, please try again"; } } } } function nextQuestion() { let qNum = document.getElementById("questionNumber").innerHTML; let num = ++qNum; if (num === 10) { num = 0; } document.getElementById("questionNumber").innerHTML = num; document.getElementById("score").innerHTML = score; document.getElementById("word").innerHTML = food[num].word; document.getElementById("image").innerHTML = ""; let imgSrc = food[num].img; let img = document.createElement("img"); img.src = food[num].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML = ""; document.getElementById("options").innerHTML = "<button class='btn' id='1' onclick='checkAnswer(food[" + num + "].ID,this)'></button> " + "<button class='btn' id='2' onclick='checkAnswer(food[" + num + "].ID,this)'></button> " + "<button class='btn' id='3' onclick='checkAnswer(food[" + num + "].ID,this)'></button>"; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name; debugger; } function prevQuestion() { let qNum = document.getElementById("questionNumber").innerHTML; let num = --qNum; if (num === -1) { num = 10; } document.getElementById("questionNumber").innerHTML = num; document.getElementById("score").innerHTML = score; document.getElementById("word").innerHTML = food[num].word; document.getElementById("image").innerHTML = ""; let imgSrc = food[num].img; let img = document.createElement("img"); img.src = food[num].img; img.width = '500'; img.height = '300'; document.getElementById("image").appendChild(img); document.getElementById("options").innerHTML = ""; document.getElementById("options").innerHTML = `<button class='btn' id='1' onclick='checkAnswer(food[` + num + `].ID,this)'></button> <button class='btn' id='2' onclick='checkAnswer(food[` + num + `].ID,this)'></button> <button class='btn' id='3' onclick='checkAnswer(food[` + num + `].ID,this)'></button>`; document.getElementById("options").getElementsByTagName('button')[0].innerHTML = food[num].options[0].name; document.getElementById("options").getElementsByTagName('button')[1].innerHTML = food[num].options[1].name; document.getElementById("options").getElementsByTagName('button')[2].innerHTML = food[num].options[2].name; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Game</title> </head> <body id="gameBody" onload="InitGame()"> <h1>Welcome to the game</h1> <h3 class="header">Your score</h3> <h3 class="text" id="score"></h3> <h5 class="header">Choose the right answer</h5> <p class="header">The question number</p> <p class="text" id="questionNumber"></p> <p class="header">The word you need to translate</p> <p id="word"></p> <div id="image"> </div> <div id="options"> </div> <p id="message"></p> <button class="myChoise" onclick="prevQuestion()">Previous</button> <button class="myChoise" onclick="nextQuestion()">Next</button> </body> </html>
Display Array Data in Table
I have a div with id="result", I want to show my data in this div tag. How to append this table data. I did not understand in table data tag table is in the string so how it works function displayAddress() { if (flag == 0) { tabledata = "<table style='position: fixed; background-color:lightgrey; border: 1px solid black; border-collapse: collapse; margin-top: 25px;' border = '1'><tr><th>Name</th><th>Type</th><th>Address</th><th>Email</th><th>Mobile</th><th>Location</th></tr>"; } for (i = 0; i < dataArray.length; i++) { var tempname = dataArray[i].Name; var temptype = dataArray[i].Type; var tempaddress = dataArray[i].Address; var tempemail = dataArray[i].Email; var tempmobile = dataArray[i].Mobile; var templocation = dataArray[i].Location; //Please fill the required code to store the values in tabledata. } console.log(tabledata); if (flag == 0) { //Please fill the required code to store the table data in result. document.getElementById("name").value = ""; document.getElementsByName("type").checked = false; document.getElementById("address").value = ""; document.getElementById("email").value = ""; document.getElementById("mobile").value = ""; document.getElementById("location").value = ""; } count = 0; }
This is one way const dataArray = [{ "Name": "Joe", "Type": "Contractor", "Address": "Address 1", "Email": "Email#email.com", "Mobile": "0123456789", "Location": "At home" }, { "Name": "Jane", "Type": "Contractor", "Address": "Address 2", "Email": "Email#email.com", "Mobile": "1234567890", "Location": "At home" } ]; const tb = document.getElementById("tb"); let tr = []; dataArray.forEach(item => { tr.push('<tr><td>' + item.Name + '</td>') tr.push('<td>' + item.Type + '</td>') tr.push('<td>' + item.Address + '</td>') tr.push('<td>' + item.Email + '</td>') tr.push('<td>' + item.Mobile + '</td>') tr.push('<td>' + item.Location + '</td></tr>') }) tb.innerHTML = tr.join(""); document.getElementById("result").classList.remove("hide"); // show #table1 { position: fixed; background-color: lightgrey; border: 1px solid black; border-collapse: collapse; margin-top: 25px; } #table1 tr td { border: 1px solid black; } .hide { display:none; } <div id="result" class="hide"> <table id="table1"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Address</th> <th>Email</th> <th>Mobile</th> <th>Location</th> </tr> </thead> <tbody id="tb"></tbody> </table> </div> Alternative method using template literals dataArray.forEach(item => { tr.push(`<tr> <td>${item.Name}</td> <td>${item.Type}</td> <td>${item.Address}</td> <td>${item.Email}</td> <td>${item.Mobile}</td> <td>${item.Location}</td> </tr>`); })
for mysself I do that [very shorter] way. All the documentation is here -> https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement const resultDiv = document.getElementById('result') , myTable = resultDiv.appendChild(document.createElement('table')) // create the TABLE , rowList = [ { lib:'Names', key: 'Name' }, { lib:'Types', key:'Type' } , { lib:'Address', key: 'Address' }, { lib:'eMails', key:'Email' } , { lib:'phone', key: 'Mobile' }, { lib:'Locations', key:'Location' } ]; // sample data const dataArray = [ { Name: "Joe", Type: "Contractor", Address: "Address 1", Email: "Email_1#email.com", Mobile: "0123456789", Location: "At home"} , { Name: "Jane", Type: "Contractor", Address: "Address 2", Email: "Email_2#email.com", Mobile: "0987654321", Location: "someWhere"} ] ; dataArray.forEach(item=> { let newRow = myTable.insertRow() rowList.forEach(rowName=>newRow.insertCell().textContent = item[rowName.key]) }) // make header part at last let theHeader = myTable.createTHead().insertRow() rowList.forEach(rowName=>theHeader.insertCell().textContent = rowName.lib) /* cosmetic part */ table { border-collapse: collapse; margin-top: 25px; font-family: Arial, Helvetica, sans-serif; font-size: 10px; } thead { background-color: aquamarine; } tbody { background-color: #b4c5d8; } td { border: 1px solid grey; padding: .3em .7em; } <div id="result"></div>
there are two ways, the easy version is document.getElementById("element").innerHTML = yourArray[0] document.getElementById("element").innerHTML = yourArray[1] document.getElementById("element").innerHTML = yourArray[2] ... second way is map() method yourArray.map(item => { elements.innerHTML = item }); if you use a framework (like Vue, React) second way is more easier dont work try this var email = yourArray[0] var password = yourArray[1] var table = "<table><tr> <td>" + email + "</td><td>" + password "</td></tr></table>
Based on select field generate a table from json file
Is it possible to auto create a table from json files based on selected values. $(document).ready(function(){ $("#dropdown_change").change(function(){ alert("Selected value is : " + document.getElementById("dropdown_change").value); });
With your given json i'hv made an example. Look into this. $("#dropdown_change").change(function() { var val = $(this).val(); alert("Selected value is : " + val); var projects = PROJECTDETAILS.filter(function(pd) { return pd['Project key'] == val; }) if (projects.length) { var html = ''; projects.map(function(pro) { html += '<tr>'; for (var i in pro) { html += '<td>' + pro[i] + '</td>'; } html += '</tr>'; }) $('table').find('tr').not(':eq(0)').remove(); $('table').show().append(html); } }); var PROJECTDETAILS = [{ "Project key": "Bluesky", "Employee Name": "anusha", "Issue Id": "0011", "Charge No": "1111", "Hours": "10" }, { "Project key": "Bluesky", "Employee Name": "anusha", "Issue Id": "00123", "Charge No": "1111", "Hours": "10" }, { "Project key": "project2", "Employee Name": "kavya", "Issue Id": "00452", "Charge No": "1111", "Hours": "10" }] $(document).ready(function() { $("#dropdown_change").change(function() { var val = $(this).val(); alert("Selected value is : " + val); var projects = PROJECTDETAILS.filter(function(pd) { return pd['Project key'] == val; }) if(projects.length){ var html = ''; projects.map(function(pro){ html+='<tr>'; for(var i in pro){ html+='<td>'+pro[i]+'</td>'; } html+='</tr>'; }) $('table').find('tr').not(':eq(0)').remove(); $('table').show().append(html); } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="dropdown_change"> <option value="Bluesky">Bluesky</option> <option value="project2">project2</option> </select> <table style="display: none"> <tr><th>Project key</th><th>Employee Name</th><th>Issue Id</th><th>Charge No</th><th>Hours</th></tr> </table>
Filter a part of String
I have an array and its data shows on a table. Live Code Filter by date or by name are working well. I write some more code to show "No Data Found" if users enter a name, which is not on the list, but somehow it doesn't work. Is there any way to write a code which will show a result if users enter only last name or first name, that matches last names or first names on the list? Please give a hand. Thanks! HTML <p>From: <input class="datepicker" id="dateFrom" type="text"> To: <input class="datepicker" id="dateTo" type="text"><button class="buttApply">APPLY</button></p> Search by Name<input type="text" id="searchByName"><button type="button" id="byNamebutton">SEARCH</button><span id="errmsg"></span> <div class="text"></div> <table id="myTable" border="1" width="300" cellpadding="5"> </table> JS $( ".datepicker" ).datepicker(); var dateList =[ { name: "Mike Jenson", email: "mike_j#yesware.com", phone: "9433550193", joined: "05/23/2014", }, { name: "Jim Stevens", email: "jim_s#yesware.com", phone: "1299331944", joined: "05/22/2014" }, { name: "Paul Smith", email: "paul_s#yesware.com", phone: "4351289654", joined: "04/14/2014" }, { name: "Sarah Andrews", email: "sarah_a#yesware.com", phone: "1299332944", joined: "03/15/2014" }, { name: "Edward O'Brien", email: "edward_ob#yesware.com", phone: "4782456897", joined: "03/27/2014" }, { name: "Nicole Plano", email: "nicole_p#yesware.com", phone: "6657831564", joined: "03/30/2013" }, { name: "Peter Min", email: "peter_m#yesware.com", phone: "8893923938", joined: "01/07/2013" }, { name: "Aaron Jackson", email: "aaron_j#yesware.com", phone: "6174896315", joined: "04/11/2014" } ]; $('#byNamebutton').click( function() { var Namefilter = dateList.filter(function(NameItem) { if(NameItem.name == $('#searchByName').val()) { return NameItem.name == $('#searchByName').val(); } else { $('#mytable').append('No data found!'); } }); refreshTable(Namefilter); } ); $('.buttApply').click( function() { var filtered = dateList.filter(function(item){ return item.joined >= $('#dateFrom').val() && item.joined <= $('#dateTo').val(); }); refreshTable(filtered); } ); function refreshTable(list){ $("#myTable").html(""); for (var i=0; i< list.length; i++) { var tr="<tr>"; var td1 = "<td>" + list[i]["name"] + "</td>"; var td2 = "<td>" + list[i]["email"] + "</td>"; var td3 = "<td>" + list[i]["phone"] + "</td>"; var td4 = "<td>" + list[i]["joined"] + "</td></tr>"; $('#myTable').append(tr+td1+td2+td3+td4); } } refreshTable(dateList);
If you want your search by name to work by containing phrase and ignore case sensitive: return NameItem.name.toLowerCase().indexOf($('#searchByName').val().toLowerCase()) != -1; As for the no data found, you just need to include this in the end of your reFreshTable function: if(list.length==0){ $('#myTable').html("No Data Found"); } JSFiddle: https://jsfiddle.net/juvian/WWscZ/9/ I would also recommend If your data is not very large to change your $('#byNamebutton').click( for a $('#searchByName').keyup( to make it more responsive, as it filters as you type
For #1 add at line 91, if ($('#myTable').html() == "") { var tr="<tr>"; var td1 = "<td colspan=4>No Results Found</td></tr>"; $('#myTable').append(tr+td1); } This addresses your #2 question: indexOf returns the position of the string in the other string. If not found, it will return -1: On line 59, use this instead: return NameItem.name.indexOf($('#searchByName').val()) > -1; It will search for partial instead of entire matches. So if you search for "Mike" or "Jensen" it will return "Mike Jensen".
jQuery - output this list of objects in 3 columns
Can someone tell me how to output this list of objects in 3 columns and sort the list alphabetically? I tried else if but... CSS: .main { float:left; width:150px; background:#9c9; } .center { float:left; width:150px; background:#c9c; } HTML: <head> <script type="text/javascript"> var data = [ {name: "Dan", age: 25, desc: "test"}, {name: "Aary", age: 15, desc: "description"}, {name: "Bary", age: 15, desc: "description"}, {name: "Cary", age: 15, desc: "description"}, {name: "Dary", age: 15, desc: "description"}, {name: "Fary", age: 15, desc: "description"}, {name: "Tom", age: 18, desc: "haaha"} ]; function findName(personName){ return $.grep(data, function(item){ return item.name == personName; }); } function details(personName) { var person = findName(personName.toString())[0]; $('#description').html(person.desc); } </script> </head> <body> <div> <div class='main'> </div> <div class='center'> </div> <div id="description"> </div> </div> </body> JS: $(function () { for (var i = 0; i < data.length; i++) { if (i % 2 == 0) { $('.main').append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>"); } else { $('.center').append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>"); } } }); http://jsfiddle.net/KKYZj/8/
You just need to add another div column: <div class='right'></div> And then change your javascript to: $(function () { data.sort(function (a, b) { return a.name > b.name; }); for (var i = 0; i < data.length; i++) { var target = [$('.main'), $('.center'), $('.right')][i % 3]; target.append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>"); } });
Look here. Ok. I put all data items in same containers with float: left; property. When need to break line and start new row of items we put <br style="clear: both"> element depending on condition if(i%3 == 0) where 3 is column count. Also I modified click handlers for elements. js: var data = [ {name: "Dan", age: 25, desc: "test"}, {name: "Aary", age: 15, desc: "description"}, {name: "Bary", age: 15, desc: "description"}, {name: "Cary", age: 15, desc: "description"}, {name: "Dary", age: 15, desc: "description"}, {name: "Fary", age: 15, desc: "description"}, {name: "Tom", age: 18, desc: "haaha"} ]; function findName(personName){ return $.grep(data, function(item){ return item.name == personName; }); } $(function() { for(var i=1;i<data.length;i++) { var dataItem = "<a href='#' class='dataItem' data-description='" + data[i].desc + "'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a>"; $('.main').append(dataItem); if(i%3 == 0) { $('.main').append("</br>") ; } } var description = $('#description'); $('a.dataItem').on('click', function(e){ description.text($(this).data('description')); }) }); html: <div> <div class='main'> </div> <div id='description'></div> </div> css: .main a{ display: block; float:left; width:150px; background:#9c9; } Don`t need to put js code and html, body, head tags in html area