Loading from json into HTML/JavaScript - javascript

so I am doing a small project in which I need to put some data about products into a json file, and then load that data into the JavaScript section of the html code. The problem is that I keep getting errors like Microsoft Visual Code is telling me that the object I am trying to load is underfined.
Here is my JSON file:
{
"Data" :
[
{"Name": "Widget", "Price": 25.00, "Quantity": 5 },
{"Name": "Thing", "Price": 15.00, "Quantity": 5 },
{"Name": "Doodad", "Price": 5.00, "Quantity": 10 }
]
}
And here is my code from the HTML page.
<form id="form1">
What product do you wish to search for? <input name="name" type="text" size="20">
</form>
<button onclick="outputprodus()">Submit
</button>
<script type="text/javascript" src="Vlad.json"></script>
<script>
var userdata = JSON.parse(Data);
var produs1_nume = userdata[0].Name;
var produs1_pret = userdata[0].Price;
var produs1_cantitate = userdata[0].Quantity;
function outputprodus(){
var x, y;
x=document.getElementById("form1");
y=x.elements["name"].value;
document.write(y+" este produsul cautat.");
document.write("<br>");
document.write(produs1_nume+" costa "+produs1_pret+" pentru "+produs1_cantitate+" bucati");
}
</script>
Am I loading the data wrong, or making some mistake afterwards?

You were loading json as script.
Here is how to load a file from network.
Codepen: https://codepen.io/kishin-karra/pen/ExVqzRw?editors=1010
var userdata = null;
var produs1_nume = null;
var produs1_pret = null;
var produs1_cantitate = null;
fetch('https://s3.ap-south-1.amazonaws.com/com.instadl.test-assets-123/Vlad.json').then(res => {
res.json().then((data) => {
userdata = data.Data;
produs1_nume = userdata[0].Name;
produs1_pret = userdata[0].Price;
produs1_cantitate = userdata[0].Quantity;
})
})
function outputprodus() {
var x, y;
x = document.getElementById("form1");
y = x.elements["name"].value;
document.write(y + " este produsul cautat.");
document.write("<br>");
document.write(produs1_nume + " costa " + produs1_pret + " pentru " + produs1_cantitate + " bucati");
}

Related

How to make Excel file that has been converted to JSON load to table (DataTables) automatically

so i got this assigment, i need to load CSV file into html page,
after i loaded it, i need to make a code that run automatically -
getting the object field name - put it in the table head, and the match the value to each of the object field name.
everything neeed to be automtically (because our teacher is going to check just by adding the csv file - nothing can be hard coded.
we also need to use library called Data Tables.
i managed to do some of the assigment, but most of it is hard coded so it is not good.
here is my html -
<table id="table_id" class="display">
<thead>
<tr id="FieldNames">
</tr>
</thead>
<tbody id="Values">
</tbody>
</table>
and to thid table i added this code -
(with hard coded JSON just to see if i can do it before i import CSV file)
const Json =
[
{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}];
$(document).ready(function () {
var Obj = Json[0];
var KeyNames = Object.keys(Obj)
for (let i = 0; i < KeyNames.length; i++) {
var Head = $(`<th>${KeyNames[i]}</th>`);
$("#FieldNames").append(Head);
}
for (let j = 0; j < Json.length; j++) {
var firstVal = Json[j].name
var secondVal = Json[j].age
var thirdVal = Json[j].email
var fourthVal = Json[j].address
var Data = `
<tr class="middle">
<td>${firstVal}</td>
<td>${secondVal}</td>
<td>${thirdVal}</td>
<td>${fourthVal}</td>
</tr>
`;
$("#Values").append(Data);
}
$('#table_id').DataTable();
});
even though the result is good, it is not what i asked to do.
im trying to figure out ways to make it run automatically but it's not working so well for me..
Alright, I did it a while ago, here's the solution:
I separated my logic into two sections:
1) Create headers:
Loop through the children Objects (as in the Objects in the array) and then get their keys with Object.keys()
The keys are your headers. Then throw them in a row inside thead and voila, your headers
2) Create the fields. This is a bit more complicated.
Loop through the main objects and that will give you the objects one by one as the loop unfolds. Then, create a row for each index. Get the values of each object, and make sure you throw them in the correct row as a td by doing something like I did id='object-" + childIndex + "'. Then grab that specific row, and after you get Object.values() from your object, throw them one by one with a loop inside of the row. TA DA
P.S. Don't ask me why I used jquery. I used it because I'm not a masochist to do this with pure JS
const json = [{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}
];
//get headers and create them
const table = $("table");
const thead = $("thead");
var promiseMe = new Promise(function(resolve, reject) {
//to create the headers first based on the objects
var createHeaders = json.forEach((childObjects, index) => {
const kNames = Object.keys(childObjects);
for (let [index, name] of kNames.entries()) {
const actualName = name.replace(/\s+/g, '')
let divId = name.replace(/\s+/g, '-');
let element = document.getElementById(divId);
if (!element) {
thead.append("<td class='header-name' id='" + divId + "'>" + name + "</td>")
}
}
resolve(createHeaders);
})
}).then(createFields());
function createFields() {
const keyNames = Object.values(json);
keyNames.forEach((childObject, childIndex) => {
//create a row for each object
const valArray = Object.values(childObject);
$("#Values").append("<tr id='object-" + childIndex + "' class='rows table-row'></tr>")
valArray.forEach((value, index) => {
$("#object-" + childIndex).append("<td class='cell'>" + value + "</td>")
})
})
}
.cell, .header-name {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_id" class="display">
<thead>
</thead>
<tbody id="Values">
</tbody>
</table>

Parse JSON foreach with JS, shows HTML list

I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:
<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->
However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:
{
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
}
This is my .js file:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("test").innerHTML = myObj.AppName;
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
This is in my HTML file
<p id="test"></p>
Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!
Firstly note that you can only have li elements as children of <ul> or <ol>, so the p element needs to be changed.
The AppName property is part of the objects within data, so you will need to either loop through them:
myObj.data.forEach(function(o) {
document.getElementById("test").innerHTML += '<li>' + o.AppName + '</li>';
}
Or access them, individually by index:
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>'; // first item only
var myObj = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>';
<ul id="test"><li>
If you just want a list of the AppName properties, you could do something like the below with jQuery. See the comments in the code for details:
// Below is the JSON string from the OP's link
let json = '{"data":[{"AppId":3,"AppName":"AnimojiStudio","AppSlug":"animojistudio","AppIcon":"https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa","AppVersion":"1.2.2","AppSize":"2.1"},{"AppId":2,"AppName":"Cute Cut Pro","AppSlug":"cute-cut-pro","AppIcon":"http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa","AppVersion":"","AppSize":""}]}';
// Parse the JSON string into a JS object
json = JSON.parse(json);
let html = "";
// Loop over the object and append a list item for each AppName property.
$.each(json.data, function (index, item) {
html += "<li>" + item.AppName + "</li>";
});
// Append the list to the div.
$("#container").append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div id="container"></div>
Using forEach loop and append. Inserting li inside a p tag is not a good idea even though it works. Convert the p into a ul/ol
var data = {
"data": [{
"AppId": 3,
"AppName": "AnimojiStudio",
"AppSlug": "animojistudio",
"AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
"AppVersion": "1.2.2",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "Cute Cut Pro",
"AppSlug": "cute-cut-pro",
"AppIcon": "http:\/\/is2.mzstatic.com\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
"AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
"AppVersion": "",
"AppSize": ""
}]
}
data.data.forEach(e =>$('#test').append('<li>' + e.AppName + '</li>' + "<br>"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>
You can use map() since you have an array inside myObj. What you want to do is returning a li with AppName value
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var ul = document.getElementById("myUl");
var li = document.createElement('li');
var data = myObj.data;
data.map(app => {
li.textContent = app.AppName;
ul.appendChild(li);
})
}
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();
You have your object, and it is parsed so let's concentrate on doing something with that object:
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
Now we have that, let's use it in different ways. myObj contains an array called data here. That array is an array of JavaScript objects, each with properties like "AppId", "AppName" etc. which we can access either directly or through an index. So, let's put up some examples of how to do that. Comments in the code
var myObj = {
"data": [{
"AppId": 1,
"AppName": "AppName1",
"AppSize": "2.1"
}, {
"AppId": 2,
"AppName": "AppName2",
"AppSize": ""
}]
};
// Here I create a Bootstrap tab and contents
// call to create a new element on the DOM
function additem(item) {
let lt = $('#list-tab');
let ltc = $('#debug-tabContent');
let thing = item.name;
let thingId = "list-" + thing;
let thingTabId = thingId + "-list";
let ttab = $('<a />')
.addClass('list-group-item list-group-item-action')
.data('toggle', "list")
.prop("id", thingTabId)
.attr('role', 'tab')
.prop('href', '#' + thingId)
.html(item.name);
ttab.appendTo(lt);
let lc = $('<div />')
.addClass('tab-pane fade')
.prop("id", thingId)
.attr('role', 'tabpanel')
.text(JSON.stringify(item.obj));
// .text("test");
lc.appendTo(ltc);
}
// * cheat, put the objects in a bootstrap tab content list
additem({
name: "myObj",
obj: myObj
});
additem({
name: "myObjW",
obj: window["myObj"]
});
additem({
name: "data",
obj: myObj.data
});
additem({
name: "data0",
obj: myObj.data[0]
});
additem({
name: "AppName",
obj: myObj.data[0].AppName
});
// pure JS walk
// Here I create a LI list as a Bootstrap list group
let len = myObj.data.length;
let myP = document.getElementById("test");
let myReg = document.getElementById("mylist-reg");
let newUl = document.createElement("ul");
newUl.classList.add('list-group');
newUl.classList.add('list-group-primary');
for (var i = 0; i < len; i++) {
let newLi = document.createElement("li");
let newContent = document.createTextNode(myObj.data[i].AppName);
newLi.appendChild(newContent);
newLi.setAttribute("id", "app-" + myObj.data[i].AppId); //has to be unique
newLi.setAttribute("class", "list-group-item");
newUl.appendChild(newLi);
}
// put the list after the paragraph
document.body.insertBefore(newUl, myP);
let myLast = document.getElementById("app-2");
myLast.classList.add("active");
//activate the bootstrap tab clicks
$('#list-tab').on('click', 'a', function(e) {
e.preventDefault();
$(this).tab('show');
});
// just do it as strings
let html = "";
for (var i = 0; i < len; i++) {
let textel = "<li id='app-js-" + myObj.data[i].AppId + "'>" + myObj.data[i].AppName + "</li>";
html = html + textel;
}
myReg.innerHTML = html;
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let textel = "<li id='app-jq-" + el.AppId + "'>" + index + ":" + el.AppName + "</li>";
$('#mylist-jq').append(textel);
});
// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
let elid = 'app-jq2-' + el.AppId;
$("<li />").prop("id", elid).text(el.AppName)
.appendTo('#mylist-jq2');
});
.list-group-item {
border: 1px lime solid
}
.list-item-last {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" />
<ul id="mylist-reg"></ul>
<ul id="mylist-jq"></ul>
<ul id="mylist-jq2"></ul>
<p id="test" class="row">put stuff after here</p>
<div class="row">
<div class="col-4">
<div class="list-group" id="list-tab" role="tablist">
</div>
</div>
<div class="col-8">
<div class="tab-content" id="debug-tabContent">
<div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">Click a tab to see one.</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>

How to pull data from a Jsonfile with javascript/jquery

I´m trying to build a dynamic basket from a JSONfile.
I first started with this file:
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"","voucher":"","currency":"","orderVat":0.0,"orderSum":0.0,"items":[]}}
And with this script I managed to pull info from the different settings and append them to existing html in my basket as you can see in this fiddle:
http://codepen.io/anon/pen/XKKbJL
var nameDiv = document.createElement("td");
nameDiv.id = 'totalIncEx';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#totalIncEx").appendTo("tr.ordersum");
var nameDiv = document.createElement("td");
nameDiv.id = 'vatTotal';
var text3 = document.createTextNode(retailerData.order.orderVat);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#vatTotal").appendTo("tr.ordervat");
var nameDiv = document.createElement("td");
nameDiv.id = 'orderTotal';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#orderTotal").appendTo("tr.ordersumtotal");
Now I have an updated JSON file with data per added product.
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"0","voucher":"","currency":"SEK","orderVat":3322.5,"orderSum":13290.0,"items":[{"qtyAvail":0,"price":6295.0,"qty":1,"artno":"DEL-17812033.10-4","label":"E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard","category":"Computers - Notebooks","manufacturer":"Dell"},{"qtyAvail":31,"price":6995.0,"qty":1,"artno":"20BV001KUK","label":"Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive","category":"Computers - Notebooks","manufacturer":"Lenovo"}]}}
In this field I have info from two different added products. I need to pull data from both of them and have the data separated in their own child element so I can display each product in the basket.
How do I pull for example the price for each product and have that placed in each own child to .carttable in this fiddle?
http://codepen.io/anon/pen/yJJNYZ
var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"orderno": "0",
"voucher": "",
"currency": "SEK",
"orderVat": 3322.5,
"orderSum": 13290.0,
"items": [{
"qtyAvail": 0,
"price": 6295.0,
"qty": 1,
"artno": "DEL-17812033.10-4",
"label": "E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard",
"category": "Computers - Notebooks",
"manufacturer": "Dell"
}, {
"qtyAvail": 31,
"price": 6995.0,
"qty": 1,
"artno": "20BV001KUK",
"label": "Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive",
"category": "Computers - Notebooks",
"manufacturer": "Lenovo"
}]
}
}
$.each(retailerData.order.items,function(i,v){//get the item
var div = $('<div/>')
div.append('item '+ '<span>'+ v.artno+'</span>' + '<span>'+ v.price+'</span>' )
$('.carttable').append(div)
})
var nameDiv = document.createElement("td");
nameDiv.id = 'totalIncEx';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#totalIncEx").appendTo("tr.ordersum");
var nameDiv = document.createElement("td");
nameDiv.id = 'vatTotal';
var text3 = document.createTextNode(retailerData.order.orderVat);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#vatTotal").appendTo("tr.ordervat");
var nameDiv = document.createElement("td");
nameDiv.id = 'orderTotal';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#orderTotal").appendTo("tr.ordersumtotal");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="carttable">
</div>
<table class="cartfacts" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr class="ordersum"><td class="cost costwide">Summa exkl. moms:</td></tr>
<tr class="ordervat"><td class="cost costwide">Moms:</td></tr>
<tr class="ordersumtotal"><td class="cost costwide">Att betala:</td></tr>
</tbody></table>
Its simple.
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"0","voucher":"","currency":"SEK","orderVat":3322.5,"orderSum":13290.0,"items":[{"qtyAvail":0,"price":6295.0,"qty":1,"artno":"DEL-17812033.10-4","label":"E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard","category":"Computers - Notebooks","manufacturer":"Dell"},{"qtyAvail":31,"price":6995.0,"qty":1,"artno":"20BV001KUK","label":"Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive","category":"Computers - Notebooks","manufacturer":"Lenovo"}]}}
$.each(retailerData.order.items,function(key,value){//get the item
document.write(value.artno + " costs " + value.price);
document.write("<br/>");
//or you get each key value in key, value
//so you can easily
document.write("<p>"+value.label+"</p>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Output array to element classes

I'm trying to output a JSON object to different parts of an HTML page using the same classes.
I'm importing my JSON from an API but when I've put information into it (via input fields) it looks a little bit like this:
{
"trip": [
{ // the first object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "12:04"
},
"destination": {
"name": "Albany",
"time": "1:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "2:05"
},
"destination": {
"name": "Boston",
"time": "3:12"
}
}]
},
{ // the second object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "1:04"
},
"destination": {
"name": "Albany",
"time": "2:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "3:05"
},
"destination": {
"name": "Boston",
"time": "4:12"
}
}]
}]
}
I'm trying to display the information on my website, but I can't get it to behave the way I want it to.
The first time around I did it something like this (after fetching the JSON via my PHP-page):
function addDataToHTML(data){
var trips = data.trip;
$.each(trips, function(){
document.getElementById('show_all_results');
var summary = document.createElement('div');
summary.innerHTML = "<span class='origin_time'>" + this.leg[0].origin.time +
" </span><span class='origin_name'> " + this.leg[0].origin.name +
"</span><span>-</span><span class='destination_time'>" + this.leg[leg.length-1].destination.time +
" </span><span class='destination_name'> " + this.leg[this.leg.length-1].destination.name +
"</span>";
document.getElementById('show_all_results').appendChild(summary);
});
}
This works but the problem I'm having is that I want to add a button in the code which would give me more information via a display:block/none-functionality. The button (and the rest of the information) would be created similarly with me having to write it in the innerHTML part of the JS, but all the ways that I've tried haven't worked and I guess it's all about me creating the divs and other DOM objects in the JS code which means that the HTML doesn't really recognize them.
Anyhow, to get more control of the code I'm now trying something like this with the HTML:
<div id="show_all_results">
<div id='search_result_single'> // First results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
<div id='search_result_single'> // Second results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
...and so on.
</div>
The JS:
for (var i = 0; i < this.leg.length; i++) {
var originName = document.getElementsByClassName("origin_name");
var originTime = document.getElementsByClassName("origin_time");
var destTime = document.getElementsByClassName("destination_time");
var destName = document.getElementsByClassName("destination_name");
for (var x = 0; x < originName.length; x++) {
var originNameItem = originName[x];
originNameItem.innerHTML = this.leg[0].origin.name;
}
for (var y = 0; y < originTime.length; y++) {
var originTimeItem = originTime[y];
originTimeItem.innerHTML = this.leg[i].origin.time;
}
for (var z = 0; z < destTime.length; z++) {
var destTimeItem = destTime[z];
destTimeItem.innerHTML = this.leg[this.leg.length - 1].destination.time;
}
for (var a = 0; a < destName.length; a++) {
var destNameItem = destName[a];
destNameItem.innerHTML = this.leg[this.leg.length - 1].destination.name;
}
}
Is there anybody that can help me get each part of the leg-array into different parts of the page using the same classes as I've done? Or is there a better way?
This became really long, sorry about that, but please let me know if I can provide any additional information. Thanks!

How do i make text = integers

I have a problem that i've been trying to solve for days.
I was wondering if it was possible to let a text turn into an integer.
So everytime i write in my textarea("ALC") Load, then on the textarea("MLC") 001. And also including 1-15 to binary at the end
E.g. Load #1 will show 001 0 00001
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC()";" /></p>
</form>
<script type= "text/javascript">
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = parseInt(x);
var bin = x.toString(2);
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
I think I understand what you want to do. You want to use what you type into "ALC" as a key to a value. In that case, you want to use a javascript object and assign the instructions as keys, and the binary to the value. Such as
var instruction_set = {
"Load" : "001",
"Store" : "010",
"Add" : "011",
"Sub" : "100",
"Equal" : "101",
"Jump" : "110",
"Halt" : "111"
}
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
x = instruction_set[x];
}
Updated:
Try this:
<html>
<head>
<center><font size ="24"> Simple Assembler </font></center>
<script type="text/javascript">
var Load = "001";
var Store = "010";
var Add = "011";
var Sub = "100";
var Equal = "101";
var Jump = "110";
var Halt = "111";
var # = "1";
</script>
</head>
<body>
<form name="AssemblyLanguagecode" action="" method="">
<textarea Id="ALC" style="resize:none;width:35%;height:35%;margin-left:15%" value="">Insert Assembly Language Code</textarea>
<textarea Id="MLC" style="resize:none;width:35%;height:35%;" ReadOnly="True">Machine Language Code will be displayed here</textarea><br />
<p align="center"><input type="button" value="Assemble" onclick="ALCtoMLC();" /></p>
</form>
<script type= "text/javascript">
var Dict = { 'Load':"001",'Store':"010"}; //example Instruction set
function ALCtoMLC() {
var x = document.getElementById("ALC").value;
var instrType = '';
for (var instr in Dict){
var ind = x.indexOf(instr);
if( ind > -1){
instrType = instrType + Dict[instr];
x = x.replace(instr,'');
}
}
console.log(instrType, "::", x);
x = parseInt(x);
var bin = x.toString(2);
bin = instrType + bin;
document.getElementById("MLC").innerHTML = bin;
}
</script>
</body>
</html>
Lets say you have a way to get the tokens. Then your function should look like this
var tokens = getTokens( document.getElementById("ALC").value ) ;
var vocabulary = { "Load" : "001" , " ... " } ;
var output = []
var i = 0;
var tokensLength = tokens.length;
for ( ; i < tokensLength; i++){
var token = tokens[i];
if ( isNaN(token) && typeof(vocabulary[token]) != "undefined" ){
output.push( vocabulary[token] );
}else if ( !isNaN(token) ){
output.push( Number(token).toString(2) );
}else{
console.log(["error : unknown token ", token]);
}
}
document.getElementById("MLC").value = output.join(" ");
I see in the question that Load translates to 0010 and not 001, so I would simply modify the vocabulary.
Explanation :
I assume you have a way to split the input to tokens. (the ALC syntax is still unclear to me).
The tokens array will contains, for example ["Load","#","15", "Load","#","16"] and so on.
Then I loop on the tokens.
If a token is a number - I turn it to binary string.
If the token is translatable by vocabulary - I switch it to its binary representation.
Otherwise I print an error.
NOTE: if output should be padded with "0" - even though it is not specified in the question, I would use "0000".substring(n.length) + n
This is how I would do it:
var opcodes = {
Load: 1,
Store: 2,
Add: 3,
Sub: 4,
Equal: 5,
Jump: 6,
Halt: 7
};
var assemblyTextarea = document.querySelector("#assembly");
var machineTextarea = document.querySelector("#machine");
document.querySelector("#assemble").addEventListener("click", function () {
var instruction = assemblyTextarea.value.split(" ");
var operand =+ instruction[1].slice(1);
var opcode = instruction[0];
var code = opcodes[opcode] * 16 + operand;
var bits = ("0000000" + code.toString(2)).slice(-8);
machineTextarea.value = bits;
}, false);
See the demo here: http://jsfiddle.net/fs5mb/1/
The input should be formatted as follows: Load #15

Categories

Resources