0

I have got two php-generated values: abc and 123. This is example ready HTML document.

<script>
  var a = 'abc';
  var b = '123';
  function changeValue()
  {

  }
</script>

<button onclick="changeValue()">

<script>
  var c = 'xyz';
</script>

and I don't know how to replace value of var c when button is clicked. What function should I use in changeValue()? Please, show me right direction, then i'll find solution bedause now I have got no idea how to deal with var value.

5
  • What magic replacement are you looking for? Please elaborate Commented Feb 4, 2016 at 16:16
  • You should always put all scripts within one <script> block. Commented Feb 4, 2016 at 16:18
  • 1
    function changeValue() { c = "xyz"; } but define c globally i.e. without var. Commented Feb 4, 2016 at 16:19
  • magic is only a custom name. Point is `how to change value' after page is ready and place when i want to do change is lower than function makes chance. Commented Feb 4, 2016 at 16:20
  • Also, this questions is as basic JS as possible -.- Commented Feb 4, 2016 at 16:21

2 Answers 2

1

I make a little modification of your js:

<script>
  var a = 'abc';
  var b = '123';
  function changeValue()
  {
c = 'pqr';
alert('You just set c to pqr');
  }
</script>

<button onclick="changeValue()">Change var C</button>
<button onclick="alert(c)">Check var C</button>
<script>
  var c = 'xyz';
</script>

preview: https://jsfiddle.net/sukalogika/akeqwbgy/

You can click Change var C button, and then click Check var C button

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

2 Comments

Thanks for help!! :-) In second script I use var name without var keyword too. I dont know is it matter ir isn't Now when run changing function and when I'm trying to use c then it's new value but in html core it's still old value. WIll it not distrub?
Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

You can change the value of variable 'c' in the do_magic_replace() function.

What you need to understand is variable scope. Any variable declared outside a function is accessible to all JavaScript code on the page; therefore, you can do the following:

function do_magic_replace() {
    c = 'Some value'; // Maybe this.value()
}

Variable scope is a fundamental concept of all programming languages. You may need to look it up with regard to JavaScript.

1 Comment

You can refer to a previous answer for a more detailed explanation: What is the scope of variables in JavaScript?

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.