I have some example data:
var jasmineData = [
{
"carrierName": "Mario Bros",
"planName": "Rainbow Road",
"copay": 100,
"premium": 200,
"annualLimit": 100000
},
{
"carrierName": "Mega Man",
"planName": "Dr. Whiley",
"copay": 250,
"premium": 1000,
"annualLimit": 250000
}
]
And a function that adds this data into a table:
function addDataToTable(jasmineData) {
for(var plan in jasminenData){
var endOfTable = $('.headers').after();
endOfTable.append($('<tr class="remove_for_intial_sort"><td>' + jasminenData[plan].carrierName + '</td><td>' + jasminenData[plan].planName + '</td><td>'
+ jasminenData[plan].copay +'</td><td>' + jasminenData[plan].premium + '</td><td>' + jasminenData[plan].annualLimit + '</td></tr>'))
}
};
Does anyone know a good way to approach this for testing? I was going to test the length of $('headers') but that didn't work.
Related
I have a form which is currently doing a simple calculation. I have a button to duplicate the same form with an increment id and I need to do the calculations of the forms added independently.
var myJson = {
"platforms": [{
"name": "Sitecore",
"id": "Sitecore",
"tasktype": [{
"name": "Promobox",
"id": "Promobox",
"components": [{
"name": "Box 0",
"id": "box0",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "Video",
"components": [{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "Siab",
"tasktype": [{
"name": "Newswire",
"id": "Newswire",
"components": [{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "Task Type New",
"components": [{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function() {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function() {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$(document).ready(function() {
var calc_index = 0;
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
});
});
$(document).ready(function() {
$('#calculate').click(function() {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc1 input, #calc1 select').each(function(index) {
var input = $(this);
$(tr).append('<td class=row-' + $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor * units;
$(tr).append('<td>' + total + '</td>');
});
});
$("#clear").click(function() {
location.reload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Production Units Calculator</h2>
<div class="formset">
<form id="calc">
<label>Platform:</label>
<select id="platform" name="platform">
<option value="0">Select Platform</option>
</select>
<label>Task Type:</label>
<select id="tasktype" name="tasktype">
<option value="0">Select Task Type</option>
</select>
<label>Component:</label>
<select id="component" name="component">
<option value="0">Select Component</option>
</select>
<label>Units:</label>
<input name="units" id="units" type="number" min="0" placeholder="Input Units" />
<br />
</form>
</div>
<button id="calculate">Calculate</button>
<button id="addNew">Add New</button>
<button id="clear">Clear</button>
<table style="width:50%" id="data">
<thead>
<tr>
<th>Platform</th>
<th>Task Type</th>
<th>Component</th>
<th>Units</th>
<th>Time</th>
</tr>
</thead>
<tbody></tbody>
</table>
I was able to duplicate form with an increment ID however once the form is duplicated by clicking on add new , duplicated form doesn't work as the first one.
Please check this fiddle
You need to consider the change event for duplicate ID too.
$("#addNew").click(function() {
calc_index++;
$("#calc").after($("#calc").clone().attr("id", "calc" + calc_index));
$("#calc" + calc_index).css("display", "inline");
$("#calc" + calc_index + " :input").each(function() {
$(this).attr("name", $(this).attr("name") + calc_index);
$(this).attr("id", $(this).attr("id") + calc_index);
});
//TODO
$.each(myJson.platforms, function(index, value) {
var platform_id;
var tasktype_id;
var component_id;
pID = "#platform" + calc_index;
tID = "#tasktype" + calc_index;
cID = "#component" + calc_index;
$(pID).append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$(pID).change(function() {
$(tID, cID).find("option:gt(0)").remove();
$(tID).find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function(index1, value1) {
$(tID).find("option:first").text("Select Task Type");
$(tID).append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$(tID).change(function() {
$(cID).find("option:gt(0)").remove();
$(cID).find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function(index2, value2) {
$(cID).find("option:first").text("Select Component");
$(cID).append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
When I run the very simple following code, for some reason I get the following result in the browser console: "6 You have not watched undefined undefined." Can anyone point out my error please?
var movies = [{
title: "The Mummy",
hasWatched: true,
stars: "5 stars"
},
{
title: "About A Boy",
hasWatched: true,
stars: "5 stars"
},
{
title: "It",
hasWatched: false,
stars: "5 stars"
},
{
title: "Cleopatra",
hasWatched: false,
stars: "5 stars"
}
];
for (var i = 0; i <= movies.length; i++) {
if (movies.hasWatched) {
console.log("You have watched " + movies.title + " " + movies.stars + ".");
} else {
console.log("You have not watched " + movies.title + " " + movies.stars + ".");
}
}
You have an array of objects so you need to reference the index of each array element. You also need to reduce your loop by one since array indexes are zero-based but the length is not.
var movies = [{
title: "The Mummy",
hasWatched: true,
stars: "5 stars"
},
{
title: "About A Boy",
hasWatched: true,
stars: "5 stars"
},
{
title: "It",
hasWatched: false,
stars: "5 stars"
},
{
title: "Cleopatra",
hasWatched: false,
stars: "5 stars"
}
];
for (var i = 0; i < movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
Change the for condition to i < movies.length; you have one extra iteration.
And you also need to references movies[i] to get the actual movie, for example, movies[i].title.
In the above example, the last index is 3 (items are numbered 0, 1, 2, 3), but your loop is going until 4 and will attempt to find movies[4].title and return undefined.
for (var i = 0; i <= movies.length; i++) {
if (movies[i].hasWatched) {
console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
} else {
console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
}
}
you were just missing the index identifier while accessing
I have a JSON file that contains an array of 3 objects.
When I want to display an object's attribute it display the name of it, for instance if I have an object car that has an attribute called name and has the value "FIAT" when I write car.name it displays " CAR.NAME " on the the listview instead of FIAT.
Here's my code.
$.getJSON("res/jsonFile/produits.json", function(products) {
$('#productList').empty();
$.each(products, function(i, product) {
$('#productList').append(productLink(product));
});
$('#productList').listview('refresh');
});
function productLink(product) {
var link="<li>" +
"<img src=product.pic>" +
"" +
"<h2>product.name</h2>" +
"<p>product.desc</p>" +
"<p>product.price</p>" +
"</li>";
return link;
}
and here's my JSON file
[
{
"name": "Coca Cola",
"desc": "Coca Cola",
"price": 10,
"qty": 100,
"pic": "img/coca cola.jpg"
},
{
"name": "Fanta",
"desc": "Fanta mini",
"price": 10,
"qty": 100,
"pic": "img/fanta.jpg"
},
{
"name": "Salade niçoise",
"desc": "Salade",
"price": 15,
"qty": 100,
"pic": "img/nicoise.jpg"
}
]
In your function you're printing the variable names, not their values. Use it like this instead:
function productLink(product) {
var link="<li>" +
"<img src=" + product.pic + ">" +
"<h2>" + product.name + "</h2>" +
"<p>" + product.desc + "</p>" +
"<p>" + product.price + "</p>" +
"</li>";
return link;
}
How can i loop the contacts inside my json object using javascript?
{
"success": 1,
"contacts": [
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
},
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
}
],
"fName": "Actura",
"fAdr": "langdyssen 5, 8200 Aarhus N",
"date": "14-9-2019"
}
I've tried using the code below, but it only displayed 0 and 1 at the console
$.getJSON("./ajax/get.php", {
type: "printer",
placement: "firm",
id: id
}).done(function (data) {
if (data.success == 1) {
//$('table#printerInfo').append("<tr><td>Printer ID</td><td>" + data.id + "</td></tr>").append("<tr><td>Mærke</td><td>" + data.brand + "</td></tr>").append("<tr><td>Model</td><td>" + data.model + "</td></tr>").append("<tr><td>Farve</td><td>" + data.color + "</td></tr>");
$('table td#firmName').append('<span class="glyphicon glyphicon-home"></span> ' + data.fName);
$('table td#firmAdr').append('<span class="glyphicon glyphicon-globe"></span> ' + data.fAdr);
$('table td#firmDate').append('<span class="glyphicon glyphicon-calendar"></span> ' + data.date);
for (var contact in data.contacts) {
console.log(contact);
}
console.log(data);
toolTip();
}
else {
alert("Der er sket en fejl: " + data.error);
}
});
Replaced data with test data, and due to 'too much code' ill be adding some ekstra text since i cant delete the question due to answers
Use code below instead:
for (var i in data.contacts) {
console.log(data.contacts[i]);
}
I am working with an API that is returning data in JSON format. An example of a response is this
{
"code": 200,
"count": 4,
"currentPage": 1,
"date": "2013-05-24T09:19:37.964+1000",
"executedQuery": "cafe",
"message": "OK",
"originalQuery": "cafe",
"results": [{
"aboutId": "b3ec5ac4096078f89fa4a9f3adcec930a1d4997c7cae30b026d61f8fcbf2013b",
"categories": [{
"id": "35491",
"name": "Cafes",
"sensitive": false
}],
"detailsLink": "http://www.yellowpages.com.au/nsw/mt-colah/bobbin-inn-13830124-listing.html?referredBy=TAPI-jHOsyHrSfHBBlo0IExDjXZZJx6PszwX6",
"hasExposureProducts": false,
"id": "13830124",
"listingType": "Business",
"name": "Bobbin Inn",
"primaryAddress": {
"addressLine": "1 Chase Rd",
"geoCodeGranularity": "PROPERTY",
"latitude": "-33.678276",
"longitude": "151.112964",
"mappable": true,
"postcode": "2079",
"state": "NSW",
"suburb": "Mt Colah",
"type": "PHYSICAL"
},
"primaryContacts": [{
"type": "PHONE",
"value": "(02) 9457 7170"
}],
"pureMobileBusiness": false,
…
From what i can tell there is a number of arrays in this response. I am failing however to parse this data on a create method
here is my code (this is working for this field i have defined but ... see below)
for (var i in p) {
str += blocka + uibare + p.executedQuery + " (" + p.executedQuery+ ")</div></div>";
str += blockb + uibarc + p.executedQuery + "</div></div>";
str += blockc + uibare + p.executedQuery + "</div></div>";
str += blockd + uibarc + p.executedQuery + "</div></div>";
str += blocke + uibare + p.executedQuery + "</div></div>";
}
This is working, because executedQuery is not part of the array. However if i want to get for example the "name" that appears to be part of the results array? Or am i reading it wrong?
so i tried
str += blockb + uibarc + p.results[i].name + "</div></div>";
and it won't pull any data.
results is an array that contains a single object of keys and values.
Try result[0]["name"].
More suitable to your request:
str += blockb + uibarc + p.results[0]["name"] + "</div></div>";