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.

Bejkrools
  • 1,129
  • 2
  • 17
  • 38

2 Answers2

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.

Je Suis Alrick
  • 3,404
  • 2
  • 16
  • 23
  • You can refer to a previous answer for a more detailed explanation: [What is the scope of variables in JavaScript?](http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Je Suis Alrick Feb 04 '16 at 16:44
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

sukalogika
  • 603
  • 4
  • 11
  • 18
  • 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? – Bejkrools Feb 04 '16 at 16:45
  • 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. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – sukalogika Feb 04 '16 at 16:58