how dinamically variable javascript - javascript

I am a javascript beginner, I have a multiple choice exam project where I want to get response data for each selected answer. I can do it by typing the code manually but I want to make the code efficient because the data can be more than 50 questions.
heres my best code .
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
}
let findSe = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
rubahtombol1.classList.remove("btn-secondary");
rubahtombol1.classList.add("btn-primary")
}
let findSe1 = () => {
let selected = document.querySelector("input[name='optionTrue2']:checked").value;
var soalId = document.getElementById("idSoal2").value;
var opsiPilih = document.getElementById("jawaban" + selected).textContent
document.getElementById("pilihan2").textContent = ". " + opsiPilih;
rubahtombol2.classList.remove("btn-secondary");
rubahtombol2.classList.add("btn-primary")
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
i'm trying to do this but not working
var i;
for (i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
window['radio' + i] = document.querySelectorAll("input[name='optionTrue" + i + "']");
window['rubahtombol' + i] = document.getElementById("buton" + i);
window['findSe' + i] = () => {
let selected = document.querySelector("input[name='optionTrue1']:checked").value;
var soalId = document.getElementById("idSoal1").value;
console.log(selected);
var opsiPilih = document.getElementById("jawaban" + selected).textContent
console.log("aku pilih:" + opsiPilih);
console.log("id saol:" + soalId);
document.getElementById("pilihan1").textContent = ". " + opsiPilih;
window['rubahtombol'+i.classList.remove("btn-secondary")];
window['rubahtombol'+i.classList.add("btn-primary")];
}
}
radio1.forEach(radioBtn => {
radioBtn.addEventListener("change", findSe1);
});
radio2.forEach(radioBtn1 => {
radioBtn1.addEventListener("change", findSe2);
});
findSe1();
findSe2();
what i imagine is, i want do that in one looping

Your second approach looks pretty close, but you need to make i local to the loop body. See JavaScript closure inside loops – simple practical example
But you can make it a little cleaner with OOP.
class Button {
contructor(i) {
this.index = i;
this.radio = document.querySelectorAll(`input[name='optionTrue${i}']`);
this.rumbahtombol = document.getElementById("buton" + i);
this.radio.addEventListener("change", this.findSe.bind(this));
}
findSe() {
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
this.rubahtombol.classList.remove("btn-secondary");
this.rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i);
}

i did a little change from the code made by #Barmar and it worked
class Button {
contructor(i) {
let radio = [];
this.index = i;
radio[i] = document.querySelectorAll(`input[name='optionTrue` + i + `']`);
radio[i].forEach(radioBtn => {
radioBtn.addEventListener("change", this.findSe.bind(this));
});
}
findSe() {
let rubahtombol = []
let selected = document.querySelector(`input[name='optionTrue${this.index}']:checked`).value;
let soalId = document.getElementById(`idSoal${this.index}`).value;
let opsiPilih = document.getElementById("jawaban" + selected).textContent;
document.getElementById(`pilihan${this.index}`).textContent = ". " + opsiPilih;
rubahtombol = document.getElementById(`buton${this.index}`);
rubahtombol.classList.remove("btn-secondary");
rubahtombol.classList.add("btn-primary")
}
}
for (let i = 1; i <= <?= session()->get('participant')['jml_soal'] ?>; i++) {
new Button(i).contructor(i);
}

Related

Javascript - setValue returns #ERROR into a cell

I'm really new to Javascript and pretty much copied most of the code and modified it a bit. Sometimes I'm getting an error putted into a cell and sometimes the correct values. Do you know what is the issue?
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;}
I'm adding the whole code as well for reference:
function getData() {
var queryString = Math.random();
var i;
for (i=2; i < 8; i++) {
var AddressColumn = SpreadsheetApp.getActiveSheet().getRange("W1").getColumn();
//if (ValueCrypto>0)
var cellFunction1 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))*X1';
SpreadsheetApp.getActiveSheet().getRange(i,3).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,3).setValue(cellFunction1);
var cellFunction2 = '=Value(Replace(IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange(i,AddressColumn).getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange(1,AddressColumn).getValue() + '"),1,1,))';
SpreadsheetApp.getActiveSheet().getRange(i,8).clearContent(); // You can also use range.setFormula("");
SpreadsheetApp.flush();
SpreadsheetApp.getActiveSheet().getRange(i,8).setValue(cellFunction2);
}
//var cellFunction2 = '=IMPORTXML("' + SpreadsheetApp.getActiveSheet().getRange('A4').getValue() + '?' + queryString + '","'+ SpreadsheetApp.getActiveSheet().getRange('A5').getValue() + '")';
//SpreadsheetApp.getActiveSheet().getRange('C2').setValue(cellFunction2);
counter2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A12").getValue();
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(counter2+1)
if (counter2 = 3) {recordValue();}
}
function recordValue() {
SpreadsheetApp.getActiveSheet().getRange("A12").setValue(0);
var counter = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A13");
//console.log(counter)
var dateCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),2);
dateCell.setValue(new Date());
//const errorValues = ["#N/A", "#REF", "#ERROR!"];
var a = 0;
for (p=3; p < 19; p=p+3){
var Value = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(9,p);
var outputValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),(3 + a));
outputValue.setValue(Value.getValue());
a = a +1;
}
var TotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R2");
var outputTotalValue = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),17);
outputTotalValue.setValue(TotalValue.getValue());
var TotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("R5");
var outputTotalValue2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange(counter.getValue(),18);
outputTotalValue2.setValue(TotalValue2.getValue());
counter.setValue(counter.getValue() + 1);
if(counter.getValue() > 300){counter.setValue("14");}}

Multiple Group By using two look-up columns which have multi valued selection enabled on an SP 2013 list using JavaScript

So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>    -    AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.

Generate table, store values from json array

I need to create tables for each index in a given array, also i need to store those values so that my for loops sends them to the tables created.
JavaScript:
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
how can this be done?
Here is the full JS:
var index;
var data;
var parsed;
$(document).ready(function() {
$.get('policy.json', function(data){
index = data;
},"json");
});
function search(){
var movement_select = $("#movements").val();
var id = $("#idSubmit").val();
var refnr = index.refnr;
var index_movements = index.movements;
//console.log(movement_select);
//for loop to test which movement from dropdown list! Done!
for (m=0; m < index_movements.length; m++)
{
if (index_movements[m].date == movement_select)
{
movement_select = index_movements[m];
}
}
var movements = index.movements;
var movements_description = movement_select.description;
var movements_premium = movement_select.premium;
var movements_payer = movement_select.payer;
var movements_payer_id = movement_select.payer.personid;
var movements_payer_name = movement_select.payer.name;
var movements_payer_surname = movement_select.payer.surname;
var movements_payer_fullname = movements_payer_name + " " + movements_payer_surname;
var movements_owner = movement_select.owner;
var movements_owner_id = movement_select.owner.personid;
var movements_owner_name = movement_select.owner.name;
var movements_owner_surname = movement_select.owner.surname;
var movements_owner_fullname = movements_owner_name + " " + movements_owner_surname;
var components_count = movement_select.components;
for (c=0; c < components_count.length; c++)
{
console.log(components_count[c]);
}
var components = movement_select.components[0];
var components_description = movement_select.components[0].description;
var components_premium = movement_select.components[0].premium;
var components_cover = movement_select.components[0].cover;
var components_commencementdate = movement_select.components[0].commencementdate;
// table 1 --------------------------------------------------
$("#id").html(id);
$("#refnr").html(refnr);
$("#movements_payer_fullname").html(movements_payer_fullname);
$("#movements_owner_fullname").html(movements_owner_fullname);
$("#refnr").html(refnr);
// table 2 --------------------------------------------------
}
and here is the JSON:
{
"policyid":"1000",
"refnr":"gcsa000923",
"movements":
[
{
"date":"2012/06/01",
"description":"Accept",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
}
]
},
{
"date":"2012/08/01",
"description":"Policy Alteration",
"premium":"R30.00",
"payer":{"personid":"928374","name":"Hansie","surname":"slim"},
"owner":{"personid":"928374","name":"Hansie","surname":"slim"},
"components":
[
{
"description":"Basic cover",
"premium":"R10.00",
"cover":"R0.00",
"commencementdate":"2012/06/01"
},
{
"description":"Cancer",
"premium":"R10.00",
"cover":"R20 000.00",
"commencementdate":"2012/06/01"
},
{
"description":"Disability cover",
"premium":"R20.00",
"cover":"R40 000.00",
"commencementdate":"2012/09/01"
}
]
}
]
}
Solved:
for (c=0; c < components_count.length; c++)
{
$('#append').append("Description: " + components_count[c].description + " " + '<br>');
$('#append').append("Premium: " + components_count[c].premium + " " + '<br>');
$('#append').append("Cover: " + components_count[c].cover + " " + '<br>');
$('#append').append("Commencement Date: " + components_count[c].commencementdate + " " + '<br>' + '<br>');
}
I forgot about .append ^^

Javascript Syntax Error "out of range"

I've been doing web development for quite sometime and have never seen this behavior with JavaScript. This is the code I started out with:
function processLogin() {
if (loginReq.readyState == 4) {
var data = eval('(' + loginReq.responseText + ')');
data = data.userData;
var focus = data.team.focus.coordinates;
thisTeam = new Team(data.team.id, data.team.missionId, data.team.name, data.team.operatingArea.coordinates[0]);
if (data.team.zoomLevel != '') {
thisTeam.zoomLevel = data.team.zoomLevel;
}
if (focus.length > 0) {
thisTeam.focusLat = focus[1];
thisTeam.focusLon = focus[0];
}
for (var i = 0; i < data.teams.length; i++) {
var temp_team = new Team(data.teams[i].id, data.teams[i].missionId, data.teams[i].name, []);
teams.push(temp_team);
}
var teamDropDownText = [];
for (var j = 0; j < teams.length; j++) {
if (thisTeam.teamId == teams[j].teamId) {
teamDropDownText.push('<option value="' + teams[j].teamId + '" selected="selected">' + teams[j].name + '</option>');
} else {
teamDropDownText.push('<option value="' + teams[j].teamId + '">' + teams[j].name + '</option>');
}
}
$('#addIncidentTeam').html(teamDropDownText.join(''));
$('#editIncidentTeam').html(teamDropDownText.join(''));
// When all this has finished, make the
// rest of the calls to get the rest of the data
startTimer();
downloadDevices();
initializeMap();
}
}
What I have written there isn't that important, and let me explain why.
The line with the single semicolon after thisTeam.zoomLevel = data.team.zoomLevel; was giving me a syntax error in firebug. I read and re-read my code, and couldn't figure out what I did wrong, so I put the semicolon on the same line as thisTeam.zoomLevel = data.team.zoomLevel and it told me it had a syntax error on the blank line!
To do another test, I moved this whole function to it's own JavaScript file and put everything after that line on one line and even tried to condense some of the code above, so now it looks like this:
function processLogin() {
if (loginReq.readyState == 4) {
var data = eval('(' + loginReq.responseText + ')');
data = data.userData;
var focus = data.team.focus.coordinates;
thisTeam = new Team(data.team.id, data.team.missionId, data.team.name, data.team.operatingArea.coordinates[0]); if (data.team.zoomLevel.length > 0) { thisTeam.zoomLevel = data.team.zoomLevel; } if (focus.length > 0) { thisTeam.focusLat = focus[1];thisTeam.focusLon = focus[0];} for (var i = 0; i < data.teams.length; i++) { var temp_team = new Team(data.teams[i].id, data.teams[i].missionId, data.teams[i].name, []); teams.push(temp_team); } var teamDropDownText = []; for (var j = 0; j < teams.length; j++) { if (thisTeam.teamId == teams[j].teamId) { teamDropDownText.push('<option value="' + teams[j].teamId + '" selected="selected">' + teams[j].name + '</option>'); } else { teamDropDownText.push('<option value="' + teams[j].teamId + '">' + teams[j].name + '</option>'); } } $('#addIncidentTeam').html(teamDropDownText.join('')); $('#editIncidentTeam').html(teamDropDownText.join('')); /* When all this has finished, make the rest of the calls to get the rest of the data */ startTimer(); downloadDevices(); initializeMap(); var kmlLink = document.getElementById('kmlLink'); var geoserverLink = document.getElementById('geoserverLink') if (user_role.substring(0, 1) == 'M') { kmlLink.href = "https://www.intelink.gov/giatstldni/hermes/webservice/kml/download/M&" + thisTeam.missionId + "&48"; kmlLink.innerHTML = "https://www.intelink.gov/giatstldni/hermes/webservice/kml/download/M&" + thisTeam.missionId + "&48"; geoserverLink.href = "https://www.intelink.gov/giatstldni/geoserver/wms/kml?layers=hermes_all&cql_filter=mission_id+=+" + thisTeam.missionId; geoserverLink.innerHTML = "https://www.intelink.gov/giatstldni/geoserver/wms/kml?layers=hermes_all&cql_filter=mission_id+=+" + thisTeam.missionId;} else { kmlLink.href = "https://www.intelink.gov/giatstldni/hermes/webservice/kml/download/T&" + thisTeam.id + "&48"; kmlLink.innerHTML = "https://www.intelink.gov/giatstldni/hermes/webservice/kml/download/T&" + thisTeam.id + "&48"; geoserverLink.href = "https://www.intelink.gov/giatstldni/geoserver/wms/kml?layers=hermes_all&cql_filter=team_id+=+" + thisTeam.id; geoserverLink.innerHTML = "https://www.intelink.gov/giatstldni/geoserver/wms/kml?layers=hermes_all&cql_filter=team_id+=+" + thisTeam.id; } } }
I did this just to see what error I would get, I knew it wouldn't work correctly. But now it's telling me there's an error on a line that doesn't exist in the file! I get:
syntax error
[Break On This Error] (10 out of range 8)
I went and commented more code out and it just made it 10 out of range 6! I don't understand!
I found the culprit. One of the values of the JSON returned was empty (no quotes or anything). Not a very helpful error message.

Need some help synch'ing outer loop counter with dialog.onconfirm()

I am writing a game for Facebook. IN the following code, I have a problem. I have a for loop executing, and in that loop, I call a dialog and implement 'onconfirm' for the dialog. The problem is that I need to access th e loop counter inside of the onconfirm function. But because the onconfirm is called outside of the scope of the for loop, the counter value is no longer valid because it's been incremented. I need some way to pass the counter value to the dialog onconfirm as it was at the time the dialog was displayed, not after the loop has finished. Or maybe someone has a better solution. Any help would be appreciated. Thanks.
function unloadCargo() {
//debugger;
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Unloading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
debugger;
if(data.unloadableCargo.length == 0) {
loadCargo();
} else {
//console.log('unloadable cargo='+dump(data.unloadableCargo));
var i = 0;
var j = 0;
var ucCount = data.unloadableCargo.length;
for(i = 0; i < ucCount; i++) {
cargoDialog = new Dialog();
cargoDialog.showChoice('Unload Cargo', 'Unload ' + data.unloadableCargo[i].goods_name + ' at ' + data.unloadableCargo[i].city_name + ' for ' + data.unloadableCargo[i].payoff + 'M euros?');
cargoDialog.onconfirm = function() {
//console.log('unloadable cargo onconfirm='+dump(data.unloadableCargo));
var ajax = new Ajax();
var param = {"city_id": data.unloadableCargo[i].city_id, "goods_id": data.unloadableCargo[i].goods_id, "payoff": data.unloadableCargo[i].payoff};
ajax.ondone = function(demandData) {
var demands = document.getElementById('demands');
var innerXhtml = '<span>';
for(var j = 0; j < demandData.demands.length; j++) {
innerXhtml = innerXhtml + ' <div class="demand-item"><div class="demand-city">' + demandData.demands[j].city + '</div><div class="demand-pay">' + demandData.demands[j].cost + '</div><div class="demand-goods">' + demandData.demands[j].goods + '</div></div>';
}
innerXtml = innerXhtml + ' </span>';
demands.setInnerXHTML(innerXhtml);
// update balance
loadCargo();
}
ajax.post(baseURL + "/turn/do-unload-cargo", param);
}
cargoDialog.oncancel = function() { loadCargo(); }
}
//loadCargo();
}
}
ajax.post(baseURL + '/turn/unload-cargo');
}
You need to pass the value to the dialog somehow.
I have never looked at the FBJS, but it seems setContext can be used for that.
Try this:
cargoDialog = new Dialog().setContext({currentIndex: i});
// showChoice is the same
cargoDialog.onconfirm = function() {
alert(this.currentIndex); // Here you should be able to get it
}

Categories

Resources