what is wrong with my javascript constructors and related syntax - javascript

EDIT: Thank you to all who responded. I'm in the process of checking it with just console.log for the desired output, but at the moment I do know that it is not doing what I want with HTML. Anyone else know what could be wrong?
Thanks!
EDIT 2: The function "functions" when I define "television" directly within the console, but other than that, I can't figure out how to have television defined in the code. I took it out of the start(); function because I thought it might be out of scope. That didn't work either.
// Program Name: Television Store
// Television Store Website.
/* Constructor Function: */
function TelInput(ret, man, scr, conf, dis) {
this.ret = parseInt(ret, 10);
this.man = man;
this.scr = parseInt(scr, 10);
this.discount = this.ret * 0.9;
this.dis = dis;
this.conf = conf
};
var start = function(){
/* Initial Variables */
var screen = prompt("Enter the screen size of TV in inches: ");
var manufacturer = prompt("Enter the manufacturer of TV: ");
var retail = prompt("Enter the retail value of TV: ");
var priceConf = confirm("Apply the 10% discount?");
var dispValues = confirm("Display Values when Finsihed?");
/* Display the Values */
console.log(television.ret);
console.log(television.man);
console.log(television.scr);
console.log(television.discount);
if(television.conf){
document.getElementById("l4").innerHtml = "Discounted Price: " + television.dis;
}
};
console.log("Program Completed."); // Confirm Javascript functions.
start(); // Start function.
var television = new TelInput(retail, manufacturer, screen, priceConf, dispValues); // Create object

If telInput is supposed to be constructor function:
Call it with new: var television = new telInput(retail, manufacturer, screen, priceConf, dispValues);. Right now the properties ret, man, etc will be assigned to window and television will be undefined.
Pascal-case constructor functions: TelInput. This is a very strong convention. See this.
A few other issues:
You are not assigning dis and conf to any property: add this.dis = dis; this.conf = conf.
this.discount = ret * 0.9; this should probably be this.discount = this.ret * 0.9; as this.ret contains the parsed value.

Related

Getting undefined for object created in callback function

I am trying to use an object I am creating from a button click event. The object is available later in the code. The last console statement prints undefined. How can I return the object for use later in the code? Thank you.
const btn = document.getElementById('btn');
// Use IIFE to get human data from form
var getUserData = (
function () {
function getInput() {
let formContainer = document.getElementsByClassName('form-container')[0];
// Remove form from screen
formContainer.classList.add('hide');
//formContainer.style.display = 'none';
let main = document.getElementById('grid');
main.classList.remove('hide');
main.classList.add('show');
//main.style.display = 'flex';
let name = document.getElementById('name').value;
let feet = document.getElementById('feet').value;
let inches = document.getElementById('inches').value;
let height = (feet * 12) + inches;
let weight = document.getElementById('weight').value;
let diet = document.getElementById('diet').value;
return { name: name, height: height, weight: weight, diet: diet};
}
return(getInput);
})();
let human;
document.getElementById("btn").addEventListener("click", function (event) {
event.preventDefault();
var user = getUserData();
human = new Human(user.name, user.height, user.weight, user.diet);
getHumanInfo(); // console logs the human
return human; // returns udefined when I try to console log later in code
});
function getHumanInfo(){
console.log(human);
}
// this returns udefined
console.log('Human: ' + human);
You are adding an event listener, so the callback won't be called before a click is performed on the element with the id btn. And you are logging the variable human immediatly: it won't be defined because it hasn't been set yet.

Passing values from an object inside a function

I have been working all day trying to pass the value of "returnData.salary" inside the "readData" function to
the object inside the "calculateTax" function which is suppose to take the salary value and calculate state and federal taxes. I am stumped, I can't find anything on the internet which provides a good example for me to work with. The examples are either way to simple or super complex. Any help would be appreciated.
I apologize in advance if I did not submit this question in the correct format. This is my first time asking for help on stackoverflow.
function readForm() {
var returnData = {};
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
$("#name2").text(returnData.name);
$("#lastName2").text(returnData.lastName);
$("#age2").text(returnData.age);
$("#gender2").text(returnData.gender);
$("#salary2").text(returnData.salary);
$("#myTextArea2").text(returnData.myTextArea);
if ($(isManager).is(':checked')) {
$("#isManager2").text("Yes");
}
else {
$("#isManager2").text("No");
}
//$("#employeeForm")[0].reset();
} //end of readForm function
function calculateTax() {
console.log("Button Works");
var calculateTax = {
state: function(num) {
num *= 0.09;
return num;
}
, federal: function(num) {
if (num > 10000) {
num *= 0.2;
return num;
}
else {
num * 0.1;
return num;
}
}
, exempt: true
};
}
//Invoke readForm function when the submit button is clicked.
$(document).ready(function () {
$("#btnSubmit").on("click", readForm);
$("#btnCalculate").on("click", calculateTax);
})
</script>
Well, simply put; you can't. Not like this anyway. Or, at least not pass the value to the function directly.
You are using global functions right now, which are not inside a class. If it was inside a class, you could instantiate the class and save it to this (which would be the class' instance). However, I'm assuming classes are a bit over complicated in this case. What you could do, is set variables globally so all functions can use them, like this;
//declare the global variable so it exists for every function
var returnData = {};
function readForm() {
//We do NOT redeclare the "var" again. It's global now.
returnData = {}; //Reset the global variable when this function is called
returnData.name = $("#name").val();
returnData.lastName = $("#lastName").val();
returnData.age = $("#age").val();
returnData.gender = $("[name=gender]:checked").val();
returnData.salary = $("#salary").val();
returnData.isManager = $("#isManager").val();
returnData.myTextArea = $("#myTextArea").val();
//Rest of your function
}
function calculateTax(){
console.log(returnData) //works here
}
Note that you do overwrite global variables, so it's best to reset them on every function call. You might get old data stuck in there, otherwise.

Getting value from a span

check out my code
It works but jsfiddle hates it for some reason.
but when it's ran in a browser i get NaN upon calculation
for some reason regardless of the parse it won't return an integer to perform calculations on.
any one have an idea why?
also
// JavaScript Document
var payment
/* requirement #2* Each input (years, loan amount, interest rate)
will have its own number pad for entry */
function getNum(id,span) {
var a;
a = parseInt(document.getElementById(id).value);
document.getElementById(span).innerHTML += a;
}
function clear1(span) {
document.getElementById(span).innerHTML = "";
}
/* requirment #7 Mortgage object with three variables: years, amount, rate */
function Mortgage(years, amount, rate) {
this.years = years;
this.amount = amount;
this.rate = rate;
/*Requirment #8. Object must have an internal function that resets all
values/variables to default and clears amounts displayed to user */
this.clearAll = function() {
document.getElementById(years).innerHTML = "";
document.getElementById(amount).innerHTML = "";
document.getElementById(rate).innerHTML = "";
}
/*gets the mortgage from spans*/
this.getCalc = function() {
/*Requirment # 9 Object must call at least 1 external function */
get();
}
}
function test() {
/*uses the params to call the spans id*/
var c = new Mortgage('yInput','lInput','rInput');
c.clearAll();
}
/* an external cunction to calculate mortgage*/
function get() {
var m = new Mortgage(parseInt(document.getElementById('yInput').innerHTML),
parseInt(document.getElementById('lInput').innerHTML),
parseInt(document.getElementById('rInput').innerHTML)
);
/* this is NaN?*/
document.write(m.years-m.rate);
}
function calculate() {
var c = new Mortgage();
c.getCalc();
}
http://jsfiddle.net/5qf7f/6/#run
In the part:
> /* this is NaN?*/
> document.write(m.years-m.rate);
Note that if the document has finished loading, a call to document.write will first call document.open, which clears the entire content of the document (including all scripts and the HTML element itself).
http://jsfiddle.net/5qf7f/6/#run
That "fiddle" doesn't work at all for me. Better to reduce your code to an absolute minimum that displays the issue and post that. The exercise will likely lead you to your problem.
It might help your investigation to know that parseInt('') returns NaN.

Javascript array is undefined... and I'm not sure why

I'm trying to translate a PHP class into JavaScript. The only thing I'm having trouble with is getting an item out of an array variable. I've created a simple jsfiddle here. I cannot figure out why it won't work.
(EDIT: I updated this code to better reflect what I'm doing. Sorry for the previous mistake.)
function tattooEightBall() {
this.subjects = ['a bear', 'a tiger', 'a sailor'];
this.prediction = make_prediction();
var that = this;
function array_random_pick(somearray) {
//return array[array_rand(array)];
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*somearray.length)];
return random;
}
function make_prediction() {
var prediction = array_random_pick(this.subjects);
return prediction;
}
}
var test = tattooEightBall();
document.write(test.prediction);
​
Works fine here, you are simple not calling
classname();
After you define the function.
Update
When you make a call to *make_prediction* , this will not be in scope. You are right on the money creating a that variable, use it on *make_prediction* :
var that = this;
this.prediction = make_prediction();
function make_prediction() {
var prediction = ''; //initialize it
prediction = prediction + array_random_pick(that.subjects);
return prediction;
}
You can see a working version here: http://jsfiddle.net/zKcpC/
This is actually pretty complex and I believe someone with more experience in Javascript may be able to clarify the situation.
Edit2: Douglas Crockfords explains it with these words:
By convention, we make a private that variable. This is used to make
the object available to the private methods. This is a workaround for
an error in the ECMAScript Language Specification which causes this to
be set incorrectly for inner functions.
To see the complete article head to: http://javascript.crockford.com/private.html
You never call classname. Seems to be working fine.
Works for me:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length;
var random = somearray[Math.floor(Math.random()*length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
}());
Were you actually calling the classname function? Note I wrapped your code block in:
([your_code]());
I'm not sure what you're trying to accomplish exactly with the class structure you were using so I made some guesses, but this code works by creating a classname object that has instance data and a pickone method:
function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
this.pickone = function() {
var length = this.list.length;
var random = this.list[Math.floor(Math.random()*length)];
return random;
}
}
var cls = new classname();
var random = cls.pickone();
You can play with it interactively here: http://jsfiddle.net/jfriend00/ReL2h/.
It's working fine for me: http://jsfiddle.net/YznSE/6/ You just didn't call classname(). If you don't call it, nothing will happen ;)
Make it into a self-executing function like this:
(function classname() {
this.list = [];
this.list[0] = "tiger";
this.list[1] = "lion";
this.list[2] = "bear";
function pickone(somearray) {
var length = somearray.length; //<---WHY ISN'T THIS DEFINED??
var random = somearray[Math.floor(Math.random() * length)];
return random;
}
var random_item = pickone(this.list);
document.write(random_item);
})();
var test = tattooEightBall();
document.write(test.prediction);
Should be:
var test = new tattooEightBall(); //forgot new keyword to create object
document.write(test.prediction()); // forgot parens to fire method
and:
this.prediction = make_prediction();
Should be:
this.prediction = make_prediction;

jquery / javascript Redefine function

Since I started this new webshop for a friend to launch, which still in progress,
I'm using the so called "jQuery fixedScroll"..
Project online: http://www.merkversterkers.com/klanten/fragma/index.php?p=shop
Everything is fine until this..
When I'm using the scrollplugin, it defines the height of the page, which a good thing..
After pressing the "filter" button the height must be predefined causing a div that will expand, and I'm unable to do that, because the document defines the height when it's loaded..
like the "$(document).ready" function
scrollfunction
$('#scart').scrollToFixed({
marginTop: $('.topbar').outerHeight() + 30,
limit: get_limit(),
zIndex: 999
});
get_limit functon
function get_limit(){
var products_row = 4;
var topbar = $(".topbar").height() + 30
var filterbar = $(".filterbar").height();
var products = products_row * 206;
if( $(".filterexpanded").css('display') == "block" ){
var expanded = $(".filterexpanded").height();
} else {
var expanded = 0;
}
var cartheight = $("#scart").height();
var limit = topbar + filterbar + expanded + products + 130 - cartheight;
return limit;
}
Can someone give me throw of some code I could try?
I would really appreciate all the help..
Without reading the question you should change this:
limit: get_limit(),
To this:
limit: get_limit,
When you are trying to set a function as a value in an object you should not use the parentheses. When you do, you are basically evaluating the function and it's value will be returned instead of the actual function.
var myObject = {
myFunction: funkyFunk()
};
function funkyFunc(){
var funkierFunction(){
// You COULD do this
};
return funkierFunction;
}
But this is what you need...
var myObject = {
myFunction: funkyFunk
};
function funkyFunc(){
// You probably want this though
}
An (untested) idea after looking at the plugin's source:
var scrollToFixedObj = $('#scart').data("ScrollToFixed");
scrollToFixedObj.options.marginTop = get_limit();

Categories