Passing an object by it's name through HTML to javascript - javascript

It's a pretty simple question and I'm going insane over here googling this all around and getting all these insanely non related answers.
here is the code:
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
var rez += key + " = "
obj.key + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja();">klikni</button>
<div id='div1'>xd</div>
Is it possible to pass an instance of an object "zut" to this function through HTML? If yes,how,if not,how am I supposed to do it through JS?
I want div1 html to be turned into:
boja = zuta
duzina = 12
thanks for answers

function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = "+ obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(zut);">klikni</button>
<div id='div1'>xd</div>

You certainly can, although why your code doesn't work is because
1) - You're re declaring the variable rezand assigning to it using += which is no valid.
2) - obj.key is not valid, because there no such property called key, To access it you need to use brackets obj[key] nowkey will be considered as a variable and it's value will be used to get the property's value.
3) - You missed a + in this line var rez += key + " = " (HERE) obj.key + "<br/>";
4) - Your call to the method in the html is missing the argument.
you can either use onclick="fja(new Banana('zuta', 12));
Or declare the object inline in the HTML, or declare it in the js and pass it name
//in the Js
var zut = new Banana("zuta", 12);
//in the HTML
onclick="fja(zut);
Example one
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = " + obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(new Banana('zuta', 12));">klikni</button>
<div id='div1'>xd</div>
Example Two
function Banana(boja, duzina) {
this.boja = boja;
this.duzina = duzina;
}
var zut = new Banana("zuta", 12);
function fja(obj) {
var rez = "";
for (var key in obj)
rez += key + " = " + obj[key] + "<br/>";
document.getElementById('div1').innerHTML = rez;
}
<button onclick="fja(zut);">klikni</button>
<div id='div1'>xd</div>

Related

Handlebars confusion I don't get it

I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys
https://codepen.io/blaze4dem/pen/zZmqKa
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options){
var radioList = options.fn();
radioList = radioList.trim().split("\n");
var output = "";
for(var val in radioList){
var item = radioList(val).trim();
output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innaHTML += tempdata;
I see 3 issues in the code.
for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.
You have a typo, when you are replacing the element. Supposed to be innerHTML
radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].
You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options) {
debugger;
var radioList = options.fn();
var hasSpaces = radioList.indexOf(' ') > -1;
var hasNewLines = radioList.indexOf('\n') > -1;
if (hasNewLines) {
radioList = radioList.trim().split("\n");
} else if (hasSpaces) {
radioList = radioList.trim().split(" ");
}
var output = "";
// for in is best to iterate over objects.
// use for loop instead
for (var i = 0; i < radioList.length; i++) {
var item = radioList[i].trim();
output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;
Check Fiddle

How to remove empty values from array in google docs script

I am trying to print out the values of the array in a google doc. I do get the correct values but it goes on printing out a number of "undefined" values. The simplest way is probably to filter out the undefined values before I print out the array.
Here is the array declaration:
var paramArr = Object.keys(e.parameter).reverse();
var tableArr = [];
for(var i = 0; i < paramArr.length - 1; i++) {
var tempArr;
var nameSelector = "Company:" + i;
var startDateSelector = "Started:" + i;
var endDateSelector = "Ended:" + i;
var referenceSelector = "Reference:" + i;
var descriptionSelector = "Description:" + i;
tempArr = [e.parameter[nameSelector] + " ",
e.parameter[startDateSelector] + " - " +
e.parameter[endDateSelector]+ "\n\n" +
e.parameter[descriptionSelector]
];
I have tried this, but it doesn't work:
tempArr = tempArr.filter(function(element){
return element !== undefined;
});

Javascript - passing returned variable to another function

I am trying to pass my results value from to projectYears() function to projectInvestment() function that will then write to the div tag. I am getting the error "result is not defined error". To me this makes sense. All the code is working as intended. Can someone please let me know how to achieve this.
function projectInvestment(nameId, investmentId, interestId, yearsId, amountId) {
var inputName = document.getElementById(nameId).value;
var inputInvestment = parseFloat(document.getElementById(investmentId).value);
var inputInterest = parseFloat(document.getElementById(interestId).value);
var inputYears = parseInt(document.getElementById(yearsId).value);
var inputAmount = parseFloat(document.getElementById(amountId).value);
projectYears(inputInvestment, inputInterest, inputYears);
var outputString = projectYears(result);
document.getElementById("outputDiv").innerHTML = outputString;
}
function projectYears(inInvest, inInterest, inYears) {
var interest = parseFloat(inInterest / 100);
var interestAmt = parseFloat(inInvest * interest);
var predictedInvest = parseFloat(inInvest + interestAmt);
var result = "<br /> Investment Schedule for <b>$" + inInvest.toFixed(2) +
" </b>at <b>" + inInterest + "% </b>annual interest for <b>" + inYears + "</b> years <br /><br />";
result += "<table border='1' align='center'><tr><th>Year</th><th>Amount</th>";
//for loop to loop through the years
for (var x = 1; x <= inYears; x++) {
result += "<tr><td>" + x + "</td><td>" + predictedInvest.toFixed(2) + "</td></tr>";
interestAmt = predictedInvest * interest;
predictedInvest = (predictedInvest + interestAmt);
}
result += "</table>";
return result;
//document.getElementById("outputDiv").innerHTML = result;
}
You are passing in a variable called result that isn't defined.
See this line in the projectInvestment function:
var outputString = projectYears(result);
It looks like, based on the function definition for projectYears, you should be passing in some of the variables you create above this line instead.
i.e.
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
var inputAmount = parseFloat(document.getElementById(amountId).value);
var outputString = projectYears(inputInvestment, inputInterest, inputYears);
document.getElementById("outputDiv").innerHTML = outputString;

Variable inside Array() is undefined

I'm having a problem with an undefined variable error. This is my code:
window.sys.Bash = {};
window.sys.Bash.version = "";
window.sys.Bash.version.major = 0;
window.sys.Bash.version.minor = 1;
window.sys.Bash.version.build = 1;
window.sys.Bash.version.release = "beta";
window.sys.Bash.printing = false;
window.sys.Bash.queue = Array();
window.sys.Bash.span = bash;
window.sys.Bash.span.input = input;
window.sys.Bash.version = ""
+ window.sys.Bash.version.major + "."
+ window.sys.Bash.version.minor + "."
+ Array(2-window.sys.Bash.version.build.toString().length+1).join('0')
+ window.sys.Bash.version.build + "-"
+ window.sys.Bash.version.release + " "
+ "(x86_64-" + window.sys.platform + ")";
delete bash; delete input;
My Web console says, that window.sys.Bash.version.build is undefined on this line:
+ Array(2-window.sys.Bash.version.build.toString().length+1).join('0')
I copied the code from here, so I don't know much about it, but it should work, huh?
You defined version as primitive, rather than object. Try this:
window.sys.Bash.version = {};
window.sys.Bash.version.major = 0;
window.sys.Bash.version.minor = 1;
window.sys.Bash.version.build = 1;
Adding properties to primitive is not an error, but the properties will be added to a temporary object that is then lost. Basically, this happened:
window.sys.Bash.version = "";
new String(window.sys.Bash.version).major = 0;
new String(window.sys.Bash.version).minor = 1;
new String(window.sys.Bash.version).build = 1;
This is described here:
Let O be ToObject(base).
Which is effectively the same as Object(str), which is effectively the same as new String(str)

parsing JSON efficiently

so I'm parsing through a JSON object like so
if(val.function1!==""){
$("#contentFunction").text(val.function1);
}
if(val.function2!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2);
}
if(val.function3!==""){
$("#contentFunction").text(val.function1 + "; " + val.function2
+ "; " + val.function3);
}
I'm wondiering if there is a better way of checking if my json object property is empty instead of having tons of conditions... this gets really messy if for instance I have up to val.function10
Thanks for your help
var strs = [];
for (var i = 0; i < 10; i++) {
var value = val["function" + i];
value && strs.push(value);
}
$("#contentFunction").text(strs.join("; "));
Something like this?
var content = "";
for (var prop in val) {
if (!val.hasOwnProperty(prop)) continue;
if (val[prop] !== "") {
content += "; " + val[prop];
}
}
Or in node.js (or modern browsers):
var c = Object.keys(val).filter(function (k) {
return val[k] !== "";
}).map(function (k) {
return val[k];
}).join("; ");
A tool like underscorejs will help you enumerate functions and properties.

Categories

Resources