Question

The following script works correctly although I need to make few amends. In each function I am getting the values need for the different formulas. However I tend to replicate the same line of code in different functions.

Ex.

function one(){ var v1= document.getElementById('one').value; }
function two(){ var v1= document.getElementById('one').value; }

Full code

I would like to declare all of the variables once and than only use the ones I need for the specific functions. If I declare them right at the top than once they are called they still hold the original value so I need to update that value to the current one if changed of course.

Was it helpful?

Solution

Your code will be very hard to read if you do it like in your fiddle.

Instead do

var myVars;
window.onload=function() {
  myVars = { 
    'list_price': document.getElementById('list_price'),
    'negotiated': document.getElementById('negotiated'),
    .
    .
    'lease_payment': document.getElementById('lease_payment')
  }

now you can do

var price = myVars.list_price.value;

or perhaps add a function

function getVal(id) {
  var val = document.getElementById(id).value;
  if (val =="" || isNaN(val)) return 0;
  return parsetInt(val,10); 
}

now you can do

var price = getVal("list_price");

OTHER TIPS

mplungjan's solution is a great one. If you're at all concerned by your global vars leaking into the window scope, wrap your code in an Immediately Invoked Function Expression to prevent that from happening:

(function(){
  // code goes here
}());

There are two ways to go about this:

  1. Update your variable when the value changes
  2. Use a function that always returns the correct value

1) You can add a listener for the change event or the keyup event that changes your global variable:

// save initial value
var val = document.getElementById('one').value;

// update the value when input is changed
addEventListener(document.getElementById('one'), 'change', function() {
  val = document.getElementById('one').value;
});

console.log(val);

2) You can use a function that always returns the current value:

var val = function() { return document.getElementById('one').value; };

console.log(val());

2b) If you hate parenthesis, you can define a property that uses the function above as a getter:

Object.defineProperty(window, 'one', {
  get : function() { return document.getElementById('one').value; }
});

console.log(one);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top