0

I am changing a global variable to the value of the input field in the HTML. I am then trying to take this value and use it inside another variable. However, this does not work, in console the value changes but not inside the variable opts. How do I make javascript pass this information successfully? Here is a link to jsfiddle where I have it running. I am trying to change the number of rays in this example: https://jsfiddle.net/9vdpt81n/

var loadValue = 1;

function val() {
    newValue = document.getElementById("input").value;
    loadValue = newValue;
}
val(opts);

var opts = {
        rays: loadValue,
        radiantSpan: loadValue,
}
8
  • 1
    There's no way to "bind" an object property to a variable like that. Commented Nov 17, 2018 at 16:27
  • Please turn this code into a runnable snippet, including the console.log so we can run it and see what you mean. Commented Nov 17, 2018 at 16:28
  • Also note that you're sending an argument to the val() function but it doesn't expect one. Commented Nov 17, 2018 at 16:29
  • Why do you call val with an argument when your function takes none? Commented Nov 17, 2018 at 16:29
  • I have added a link to jsfiddle in the question. @trincot Commented Nov 17, 2018 at 16:32

1 Answer 1

2

You can use a getter which binds a function to an Object property and uses the return value of that function each time the property is looked up.

var opts = {
    get rays(){
       return loadValue;
    },
    get radiantSpan(){
       return loadValue;
   }
}

var loadValue = 1;
var opts = {
    get rays(){
       return loadValue;
    },
    get radiantSpan(){
       return loadValue;
   }
}
function showOpts(){
console.log('opts.rays:', opts.rays);
console.log('opts.radiantSpan:', opts.radiantSpan);
} 
showOpts();
loadValue++;
showOpts();

JSFiddle: http://jsfiddle.net/af0mnywL/

Alternatively, you could set the value of the rays and radiantSpan properties of your object on the change event of the input.

function val() {
    var newValue = document.getElementById("input").value;
    loadValue = newValue;
    opts.rays = opts.radiantSpan = loadValue;
}

JSFiddle: http://jsfiddle.net/9hwfap3j/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help, I have tried this, but it does not work I get an Unexpected identifier. Please could you check the full code at: jsfiddle.net/9vdpt81n
really, great news its been hours I have been trying to work this out, could you please update the code on jsfiddle? would be so much help hev1. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.