I've created a quiz where every question is a Question object which question has methods like print quiestion and so on. I've added my questions inside the javascript file but I want to move the questions to an external Json file.
However I can't find any article that covers how two create methods for the imported Json objects (the question objects) in this case. Here is a piece of code for the quiz object with one method before using getJson:
$(function(){
// <-- QUESTION OBJECT -->
function Question(question, choices, correctChoice, userAnswer, type) {
this.question = question;
this.choices = choices;
this.correctChoice = correctChoice;
this.userAnswer = userAnswer;
this.type = type; // either radio buttons or check boxes
// <-- write question method -->
this.writeQuestion = function() {
var questionContent;
questionContent = "<p class='question'>" + (currentQue + 1) + ". " + this.question + "</p>";
var checked = "";
if(this.type === "radio") {
for(var i=0; i < this.choices.length; i++) {
if((i+1) == this.userAnswer)
checked = "checked='checked'";
questionContent += "<p><input class='css-radio' id='radio" + (i+1) + "' " + checked + " type='radio' name='choices' value='choice'></input>";
questionContent += "<label class='css-label' for='radio" + (i+1) + "'>" + this.choices[i] + "</label></p>";
checked = "";
}
}
else {
for(var i=0; i < this.choices.length; i++) {
if ((i+1) == this.userAnswer[i])
checked = "checked='checked'";
questionContent += "<p><input class='css-checkbox' id='checkbox" + (i+1) + "' " + checked + " type='checkbox' name='choices' value='choice'></input>";
questionContent += "<label class='css-label-checkbox' for='checkbox" + (i+1) + "'>" + this.choices[i] + "</label></p>";
checked = "";
}
}
return $quizContent.html(questionContent);
};
You should create a constructor function that receives the json and defines all methods there, using the json you've provided, something rough like this:
function Question(questionJson) {
var data = questionJson;
//Public "methods" are defined to "this"
this.getCorrectAnswer = function() {
return data.correctAnswer;
};
//Private "methods
var doSomethingCrazy = function() {
return "crazy";
};
this.getSomethingCrazy = function() {
return doSomethingCrazy();
};
}
And then, lets say you have an array of questions:
var questions = [
{questionId: '1', correctAnswer: 'a', possibleAnswers: []},
{questionId: '2', correctAnswer: 'a', possibleAnswers: []},
];
You do:
var instances = [];
for (var q in questions) {
instances[q.questionId] = new Question(q);
}
This code worked:
var allQuestions = [];
var category = "history";
for(var i=0; i < jsonDataLength; i++) {
allQuestions[i] = new Question(); // create empty question Obj
var questionNr = "q" + (i+1).toString(); // store questionNr in variable
for(var properties in jsonData[category][questionNr]) // loop through questionObjs properties
allQuestions[i][properties] = jsonData[category][questionNr][properties];
// add them to empty QuestionObj
}
Related
i have a quiz with radio buttons ,sow i have to save the answears on my local storge ,but im stuck i don t know what else to do,im learnig sow dont hate me pls,tnx
This is my code sow far
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<div >";
html += "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\">" + questionItem.options[i] ;
html += "</div>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
function save() {
var g1 = document.querySelector('input[type="radio]');
g1 = (g1) ? g1.value : '';
localStorage.setItem("g1", g1);
}
});
You can simplify your AJAX dialog by using fetch() instead of new XMLHttpRequest();. I straightened out a few things in your code (also see the initial remarks in #brianagulo's answer) and prepared a little set of sample data to demonstrate the whole functionality of the quiz. The jsonplaceholder.typicode.com url only serves as a working json-server endpoint. The received data is actually ignored here.
In your "production version" you will need to un-comment the line:
localStorage.setItem("quiz",JSON.stringify(ans))
The checked answers where collected in an object doing
[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
This
collects all checked radio button inputs with (document.querySelectorAll('input[type=radio]:checked')),
converts the collection of DOM elements into a proper array (with [... ])and eventually
reduce()-s its elements into an object where the element names are the property names and the (input-)element values are the property values.
And also please note that you can only store strings in local storage. Therefore I converted the ans object into a JSON string before using it in the .setItem() method.
const Q = {
quiz: [{
question: "Where was the Boston tea party?",
options: ["New York", "Detroit", "Boston", "Reno"]
}, {
question: "Where would you find Venice Beach?",
options: ["Detroit", "Venice", "Paris", "Los Angeles"]
}, {
question: "Where would you find Queens?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where is Greenwich Village?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where would you find the Gateway Arch?",
options: ["St. Quentin", "St. Louis", "St. Anton", "San Francisco"]
}]
}, quiz = document.getElementById("quiz");
var url = "quiz.json";
// in your productive version: comment out the following line
url = "https://jsonplaceholder.typicode.com/users/7"; // functioning test URL for fetch
function save(ev) {
ev.preventDefault();
const ans=[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
// in Stackoverflow snippets you cannot use local storage, so here is console.log instead:
console.log(ans);
// in your productive version: un-comment the following line
// localStorage.setItem("quiz",JSON.stringify(ans))
}
fetch(url).then(r => r.json()).then(object => {
// remove the following line:
object = Q; // use the static quiz from defined in Q instead ...
let json = object
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<label>";
html += "<input type=\"radio\" id=\"q\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\"> " + questionItem.options[i];
html += "</label><br>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
quiz.onsubmit=save;
});
<form id="quiz"> </form>
There is a typo on your save function. You are missing a quote after radio:
var g1 = document.querySelector('input[type="radio"]');
Also, your question is confusing but if what you are trying to do is get whether the radio is checked or not you must access the checked property and save that to localStorage. And if you want to save the state for all of the buttons then you should use querySelectorAll and save them that way instead. Example below of accessing a single input's checked value:
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
For saving them all
Lastly, it seems you are not actually calling the save() function. If your intention is to have the radios checked state saved to localStorage on click you may want to add an event to the submit button. For example:
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<div >";
html += "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\">" + questionItem.options[i] ;
html += "</div>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
let submitButton = document.querySelector('input[type="submit"]');
submitButton.onclick = (event) => {
/* this prevents page refresh and submission to the backend which is a form default */
event.preventDefault();
// then we call the save function here
save();
};
});
If this was helpful please consider selecting as the answer
I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
In the following:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
} // processResponse
if (weighInData[obj].user === selUser) { ... returns the following (using example Ron):
Object { user="Ron", date="2014-08-01", weight="192"}
Object { user="Ron", date="2014-08-02", weight="195"}
Object { user="Ron", date="2014-08-03", weight="198"} ... etc.
... so my problem presently is where this belongs:
var peakWeight = Math.max.apply(Math, weights);
console.log("peakWeight: " + peakWeight);
Since I'm only after the weight values for the matching user, I assumed it would have to run within the 'if (weighInData[obj].user === selUser) { ... ', but this (and numerous other attempts in and out of the loop, including a for loop within the selUser) fail to achieve the desired results. In fact, even when the math function wasn't running on each value in 'weights', (i.e., outside the loop) and only ran outside the loop, the result was an incorrect value.
Any insight is greatly appreciated,
svs
Here's a very simple example you can probably adjust to fit your purpose:
// create this array outside of for loop so it already exists
var arr = [];
// test data
var a = { user:"Ron", date:"2014-08-01", weight:"192"};
var b = { user:"Ron", date:"2014-08-02", weight:"195"};
var c = { user:"Ron", date:"2014-08-03", weight:"198"};
// within for loop, you should only need to push once (per loop)
arr.push( a.weight );
arr.push( b.weight );
arr.push( c.weight );
// after the loop ends, display loop, get max and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
http://jsfiddle.net/biz79/sb7zayze/
If i were to edit your code, something like this might work:
function processResponse(response){
var myObj = JSON.parse(response); // convert string to object
var weighInData = myObj["WEIGH-INS"];
var dataRows = document.getElementById("data-rows");
dataRows.innerHTML = "";
// ADDED: create array
var arr = [];
for (var obj in weighInData) {
if (weighInData[obj].user === selUser) { // *
var weights = JSON.parse("[" + weighInData[obj].weight + "]"); // convert to object
// ADDED: add to array
arr.push(weights);
var row = "<tr>" +
"<td class=\"date\">" + weighInData[obj].date + " </td>" +
"<td class=\"value\">" + weighInData[obj].weight + "</td>" +
"</tr>";
var userDisplayEl = document.getElementById("user-display");
userDisplayEl.innerHTML = weighInData[obj].user;
output.innerHTML += row;
} // if ... === selUser
} // for var obj in weighInData
// ADDED: after the loop ends, display loop, get max/min and display
alert(arr);
var peakWeight = Math.max.apply(null, arr);
var minWeight = Math.min.apply(null, arr);
alert("Max: " + peakWeight + " -- Min: " + minWeight);
} // processResponse