0

I have a global Variable.

var w = 4;

and a function:

function do() {
    width = w;
    //make something
}

and now i want to change the variable w to 8 with a button.

<input type="button" onclick="do(w = 8;)" value="set 8">

that the function can work with w = 8 and forget the old w = 4!

2 Answers 2

3

You need to put w in the proper scope:

var w = 4;

function do(width) {
    w = width;
    // ...
}

And then pass an argument to your function:

<input type="button" onclick="do(8)" value="set 8">
Sign up to request clarification or add additional context in comments.

Comments

-1

I'm afraid that your code is wrong, almost from start to finish. You really do need to read a book on the basic syntax of using Javscript.

That said, this will do what you asked for:

var w = 4; // Bad idea to have a global variable.  It is also unused.

function do(w) { // You pass a parameter here.
    var width = w; // no need for this because now you have a 'w'
    //make something
}


<input type="button" onclick="do(8)" value="set 8"> <!-- the value does nothing here -->

Comments

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.