This block of code is to create 3 arrays with the values pulled from the user's input in a popup menu in the HTML file, but the values here are needed to fill in the table below.
var arrM = new Array; var arrT = new Array; var arrA = new Array;
arrM[0] = mod0.mod.value; arrT[0] = mod0.target.value; arrA[0] = mod0.actual.value;
arrM[1] = mod1.mod.value; arrT[1] = mod1.target.value; arrA[1] = mod1.actual.value;
arrM[2] = mod2.mod.value; arrT[2] = mod2.target.value; arrA[2] = mod2.actual.value;
arrM[3] = mod3.mod.value; arrT[3] = mod3.target.value; arrA[3] = mod3.actual.value;
arrM[4] = mod4.mod.value; arrT[4] = mod4.target.value; arrA[4] = mod4.actual.value;
arrM[5] = mod5.mod.value; arrT[5] = mod5.target.value; arrA[5] = mod5.actual.value;
arrM[6] = mod6.mod.value; arrT[6] = mod6.target.value; arrA[6] = mod6.actual.value;
arrM[7] = mod7.mod.value; arrT[7] = mod7.target.value; arrA[7] = mod7.actual.value;
arrM[8] = mod8.mod.value; arrT[8] = mod8.target.value; arrA[8] = mod8.actual.value;
arrM[9] = mod9.mod.value; arrT[9] = mod9.target.value; arrA[9] = mod9.actual.value;
the code in between the block above and the block below(not shown here) is just to compute the average values and does not interact with the block below
the code below is to create a table with the same number of rows as the number of rows the user filled in the popup menu.
var tableGenerator = document.getElementById("tableGenerator");
tbl = document.createElement('table');
tbl.style.width = '500px';
tbl.style.height = '100px';
tbl.style.border = '1px solid black';
tbl.style.margin = '50px';
tbl.style.float = 'left';
if (j < 6) {
j = 6;
}
for (var a = 0; a < j+1; a++) {
var tr = tbl.insertRow();
for (var b = 0; b < 3; b++) {
if (a == j && b == 3) {
break;
} else {
var td = tr.insertCell();
td.appendChild(document.createTextNode(""));
td.style.border = '1px solid black';
if (a == 0 && b == 0) {
var newtext = document.createTextNode(Text);
var celltext = "Year " + year.value + " Semester " + semester.value;
td.appendChild(document.createTextNode(celltext));
td.setAttribute('colSpan', '3'); break;
}
//this else block below here obviously doesn't work, but this idea is there and I want something that
//works like the pseudo code below
else {
for (a = 1; a < j; a++) {
tbl[a][0] = arrM[a];
tbl[a][1] = arrT[a];
tbl[a][2] = arrA[a];
}
}
}
}
}tableGenerator.appendChild(tbl);
I am very unfamiliar with HTML/JS/CSS, is it possible for us to access cell values of a table as if it is an array? or is there any better way to do this?
In JavaScript you'll need to either create text nodes and assign the content of that node, or assign the content to the textContent, innerText or innerHTML properties to give the table cells their values.
td.textContent = 'Hello'; // This is the preferred property for text.
The help you achieve this it would be wise to structure your data in a way that you can loop over, because you're basically doing the same thing in a specific order. For example:
var data = [
arrM,
arrT,
arrA
];
This will put your arrays in another array. Now you can loop over the data array and create a table row for each array, and a table cell for each item in the nested array.
for (var i = 0; i < data.length; i++) {
// ... create table row.
for (var j = 0; j < data[i].length; j++) {
// ... create table cell and assign textContent property.
}
}
Examine the example below. It's a runnable version of the thing I've explained above. I hope it helps you out.
function createTable(headers, values) {
var table = document.createElement('table');
// Build <thead>
var tableHeader = table.createTHead();
// Create <tr> inside <thead>
var tableHeaderRow = tableHeader.insertRow();
for (var i = 0; i < headers.length; i++) {
// Create <th>
var tableHeaderCell = document.createElement('th');
// Set text of <th> to value in array.
tableHeaderCell.textContent = headers[i];
// Add <th> to <tr> inside <thead>
tableHeaderRow.appendChild(tableHeaderCell);
}
// Build <tbody>
var tableBody = table.createTBody();
for (var j = 0; j < values.length; j++) {
// Create <tr> inside <tbody>
var tableBodyRow = tableBody.insertRow();
for (var k = 0; k < values[j].length; k++) {
// Create <td> inside <tr>
var tableBodyCell = tableBodyRow.insertCell();
// Set text of <td> to value in array.
tableBodyCell.textContent = values[j][k];
}
}
// Add <table> to the <body>
document.body.appendChild(table);
}
var titles = [
'One',
'Two',
'Three'
];
var characters = [
['Batman', 'Robin', 'Batgirl'],
['Joker', 'Two-Face', 'Poison Ivy'],
['James Gordon', 'Alfred Pennyworth', 'Clayface']
];
createTable(titles, characters);
Could you help me with this problem I found on MDN?
var list = document.querySelector('.output ul');
var totalBox = document.querySelector('.output p');
var total = 0;
list.innerHTML = '';
totalBox.textContent = '';
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
total += price;
itemText = name + ' — $' + price;
var listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
totalBox.textContent = 'Total: $' + total.toFixed(2);
<div class="output">
<ul></ul>
<p></p>
</div>
I understand the logic but when I write only this part of the code below on my console, it returns only "Socks:5.99":
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
}
And the subArray contains only that element. It seems like the for loop doesn’t work. Shouldn’t it give me an entire new Array with:
Underpants — $6.99
Socks — $5.99
T-shirt — $14.99
Trousers — $31.99
Shoes — $23.99
Your code works, you just have to store each iteration result somewhere, like in a new array. Here is an example:
var products = [
'Underpants:6.99',
'Socks:5.99',
'T-shirt:14.99',
'Trousers:31.99',
'Shoes:23.99'
];
var formattedProducts = [];
for (var i = 0; i < products.length; i++) {
var subArray = products[i].split(':');
var name = subArray[0];
var price = Number(subArray[1]);
formattedProducts.push(name + ' - $' + price);
}
console.log(formattedProducts);
Edit
In your first code example, the result was stored directly in your DOM, inside the .output ul list element:
var listItem = document.createElement('li');
listItem.textContent = itemText;
// list is defined outside the loop and will receive a new li element with the result of the iteration as textContent
list.appendChild(listItem);
I am trying to create a form which will generate different levels of forms based on the user input.
An example of this is
"How many levels are there?" -User input 3-
Three separate levels will be generated each with the same questions. In this there will be a question asking "How many objects are there?" the same will happen here in that multiple options will be generated.
Rough sketch of how the form would be displayed
The problem I've been having with this is allocating ids and then being able to fetch them after so that they can be referenced for use and MySQL later down the line.
function generateForm(){
var number = document.getElementById('number_of_levels').value;
var div = document.getElementById('levels');
// div.innerHTML += " " +number;
var heading = document.createElement("P");
heading.innerHTML = "Level " + number;
document.getElementById('levels').appendChild(heading);
var objects = document.createElement("P");
objects.innerHTML = "How many objects is the badge comprised of?";
document.getElementById('levels').appendChild(objects);
var num_objects_input = document.createElement("input");
num_objects_input.type = "number";
num_objects_input.id = "number_objects" +number;
document.getElementById('levels').appendChild(num_objects_input);
//num_objects.onchange = function(){addObject(num_objects.id)};
//div for the following levels
var ind_levels_div = document.createElement("div");
ind_levels_div.id = "level_" +number;
document.getElementById('levels').appendChild(ind_levels_div);
num_objects_input.onchange = function(){additionalObject()};
}
function additionalObject(){
var number = document.getElementById("number_objects" +number).value;
var objects_number = document.createElement("P");
objects_number.innerHTML = "Object " + number;
document.getElementById("level_" +number).appendChild(objects_number);
}
The result I'm getting is the form won't generate any Object form elements but will make the Levels.
For building the form this code works fine. If you want to retrieve data then you should add a name attribute what data you want to retrieve.
function generateForm() {
var number = 0;
number = document.getElementById('number_of_levels').value;
var div = document.getElementById('levels');
// div.innerHTML += " " +number;
if (number > 0) {
document.getElementById('levels_btn').setAttribute('disabled', 'disabled');
}
for (let index = 0; index < number; index++) {
var heading = document.createElement("h4");
heading.innerHTML = "Level " + (index + 1);
document.getElementById('levels').appendChild(heading);
var objects = document.createElement("p");
objects.innerHTML = "How many objects is the badge comprised of?";
document.getElementById('levels').appendChild(objects);
var num_objects_input = document.createElement("input");
num_objects_input.type = "number";
num_objects_input.id = "number_objects" + (index + 1);
document.getElementById('levels').appendChild(num_objects_input);
var submit = document.createElement("button");
submit.type = "button";
submit.innerHTML = 'objects';
submit.id = "submit" + (index + 1);
submit.onclick = additionalObject;
document.getElementById('levels').appendChild(submit);
var objectdiv = document.createElement("div");
objectdiv.id = "objects_level" + (index + 1);
objectdiv.className = 'objects_level';
document.getElementById('levels').appendChild(objectdiv);
}
}
function additionalObject() {
//console.log(Number(this.id.replace("submit", "")));
var pos = Number(this.id.replace("submit", ""));
var number = document.getElementById('number_objects' + pos).value;
for (let index = 0; index < number; index++) {
var objects_number = document.createElement("p");
objects_number.innerHTML = "Object " + (index + 1);
document.getElementById("objects_level" + pos).appendChild(objects_number);
}
}
.levels {
padding-left: 20px;
}
.objects_level {
padding-left: 40px;
}
<h3>Level</h3>
<form action="/" method="get">
<input type='number' name='number_of_levels' id='number_of_levels' />
<button type='button' id='levels_btn' onclick='generateForm()' />Levels</button>
<div id='levels' class='levels'></div>
<br><br>
<button type="submit">Submit Form</button>
</form>
You can read the article https://www.w3schools.com/tags/att_form_action.asp for getting the idea of how from action works according to retrieve the data
I have a json which i'm trying to parse it using javascript. Iteration count and the pages getting appended to it are going to be dynamic.
Expected Result
Just like the above image i'm able to take dynamic iteration keys from the below mentioned json.
Iteration.json
{
"count":[
{
"iteration1":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
},
{
"iteration2":[
{
"PageName":"T01_Launch"
},
{
"PageName":"T02_Login"
}
]
}
]
}
When i click on iteration it has to populate the corresponding pagenames for that particular iteration as shown in expected result image. But what i get actually is (refer the image below):
Please find the code that i tried:
var pagenamearray = [];
$.getJSON("iteration.json", function(json) {
var hits = json.count;
var iterations, tnname, iteration;
for (var k in hits) {
var value;
if (hits.hasOwnProperty(k)) {
value = hits[k];
var iteratearray = [];
for (var j in value) {
if (value.hasOwnProperty(j)) {
j;
var check = value[j];
for (var i in check) {
if (check.hasOwnProperty(i)) {
var test = check[i];
for (var t in test) {
if (test.hasOwnProperty(t)) {
var pagename = JSON.stringify(t)
var arr = []
if (pagename.includes("PageName")) {
//alert("Key is " +pagename + ", value is" + JSON.stringify(test[t]));
for (var it = 0; it < hits.length; it++) {
if ((Object.keys(hits[it])).includes(j)) {
var pagenamevalue = test[t];
arr[it] = [];
arr.push(pagenamevalue);
}
}
}
//alert(arr)
}
pagenamearray.push(arr);
}
}
}
}
var row = document.createElement('div');
row.setAttribute("class", "row");
row.setAttribute("id", j)
var gridWidth = document.createElement('div');
gridWidth.setAttribute("class", "col-lg-12");
var panelRoot = document.createElement('div');
panelRoot.setAttribute("class", "panel panel-default");
var panelHeading = document.createElement('div');
panelHeading.setAttribute("class", "panel-heading");
var heading3 = document.createElement('a');
heading3.setAttribute("class", "panel-title");
var icon = document.createElement('i');
icon.setAttribute("class", "fa fa-long-arrow-right fa-fw");
heading3.appendChild(icon);
heading3.innerHTML = j;
heading3.setAttribute("onclick", "doit('" + j + "');");
panelHeading.appendChild(heading3);
/* var panelBody=document.createElement('div');
panelBody.setAttribute("class","panel-body");
panelBody.setAttribute("id","panellinks");*/
panelRoot.appendChild(panelHeading);
// panelRoot.appendChild(panelBody)
gridWidth.appendChild(panelRoot);
row.appendChild(gridWidth);
document.getElementById("analysis").appendChild(row);
}
}
}
});
function doit(value) {
var ul = document.getElementById(value);
if (ul != undefined) {
$("#" + "expandlinks").remove();
$("#" + value + value).remove();
}
var accordion = document.getElementById(value);
var panelBody = document.createElement('div');
panelBody.setAttribute("class", "panel-body");
panelBody.setAttribute("id", "expandlinks")
var tablediv = document.createElement('div')
var tablelink = document.createElement('a');
tablediv.appendChild(tablelink);
var graphdiv = document.createElement('div')
var graphlink = document.createElement('a');
graphdiv.appendChild(graphlink);
var recommndiv = document.createElement('div');
var recommendlink = document.createElement('a');
recommndiv.appendChild(recommendlink)
//alert(pagenamearray.length)
tablelink.innerHTML = pagenamearray;
/*graphlink.innerHTML="Timeline View";
recommendlink.innerHTML="Recommendations";*/
panelBody.appendChild(tablediv);
panelBody.appendChild(recommndiv);
panelBody.appendChild(graphdiv);
accordion.appendChild(panelBody);
}
Any advise on how to achieve this would be of great help. Thanks in advance.
I think the problem is how you assign the pagenamearray to tablelink.innerHTML. This converts the array to a string, converting all elements in the array to a string too and separating them by a comma each. However, your pagenamearray contains some empty arrays too; these will convert to an empty string in the process, but will still have a comma before and after them.
In your example code above, the pagenamearray will end up with a value of [[[],"T01_Launch"],[[],"T02_Login"],[null,[],"T01_Launch"],[null,[],"T02_Login"]] - when converted to a String, this will result in ",T01_Launch,,T02_Login,,,T01_Launch,,,T02_Login". So instead of assigning it to the innerHTML value directly, you'll first have to filter out the empty arrays and null values.
What i wanted to do is access random property for example let1, let2 with their first string in array which is ID "1" , "2" , "3" , "4" , "5".
brojleta is actually that ID i mentioned before, it is different from id down there(var id = item[0][1]). What i need is to get all other strings based on their ID. I tried it like this :
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
var location = decodeURI(window.location.toString());
var index = location.indexOf("?") + 1;
var subs = location.substring(index, location.length);
var splitted = subs.split("&");
for (i = 0; i < splitted.length; i++) {
var s = splitted[i].split("=");
var pName = s[0];
var pValue = s[1];
if (pName == brojleta) {
return pValue;
}
}
}
var brojleta = getParamValue("id");
var item = data.find(item => item[0][0] === brojleta);
var id = item[0][1]
var datumpolaska = item[0][2]
var datumdolaska = item[0][3]
var polazniaerodrom = item[0][4]
var dolazniaerodrom = item[0][5]
var brojsedista = item[0][6]
var cenakarte = item[0][7]
var data1 = data.let1[0];
var data2 = data.let2[0];
var data3 = data.let3[0];
var data4 = data.let4[0];
var data5 = data.let5[0];
/* this is the code for adding data from array to table */
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
var row3cells = $("#row3 td");
var row4cells = $("#row4 td");
var row5cells = $("#row5 td");
for (var index=0; index<8; index++) {
$(row1cells[index]).html(data1[index]);
$(row2cells[index]).html(data2[index]);
$(row3cells[index]).html(data3[index]);
$(row4cells[index]).html(data4[index]);
$(row5cells[index]).html(data5[index]);
}
});
To make your code work you should choose variable data to be an array of arrays instead of an object. Then you can run var item = data.find(item => item[0] === brojleta); and similar operations.
It would look like this:
var data = [["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"],
["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"],
["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"],
["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"],
["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]];
I think you really want this:
Remove the || 3 // test #3 after testing
Try removing the 3 from the input and click search too
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
return new URLSearchParams(document.location.search.substring(1)).get(brojleta)
}
function show(item) {
$tr = $("<tr/>"), $tbd = $("#tbd");
$.each(item,function(_,fld) {
$tr.append("<td>"+fld+"</td>");
})
$tr.appendTo($tbd);
}
function showAll() {
Object.keys(data).forEach(function(key) {
show(data[key][0]);
})
}
$(function() {
$("#search").on("click",function() {
$("#tbd").empty();
var brojleta = $("#broj_leta").val();
if (brojleta) show(data["let"+brojleta][0])
else showAll();
});
var brojleta = getParamValue("id") || 3 // test #3
if (brojleta) $("#broj_leta").val(brojleta);
$("#search").trigger("click");
})
th, td { border:1px solid lightgrey; padding: 3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="broj_leta" /><button id="search">Search</button>
<table>
<thead>
<tr>
<th>id</th>
<th>Datumpolaska</th>
<th>Datumdolaska</th>
<th>Plazniaerodrom</th>
<th>Dolazniaerodrom</th>
<th>Brojsedista</th>
<th>Cenakarte</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>
You can first filter the data based on ID and then map your required variable to final output array in below code output.
var brojleta = 1;
const mappedarray = Object.entries(data).filter((k,v)=>{return k[0] == "let"+brojleta});
console.log(mappedarray[0][1][0]);
You can use the lodash function find().
This is the same function as Array.find but it works on Object.
https://lodash.com/docs/4.17.11#find