Maurizio Benini
Maurizio Benini

Reputation: 11

increment a variable with javascript

I have made this script, but there is a problem.

When i click addbutton the variable on console log recieve the update (1, 2 ,3 ,4) for every click.

But var fieldHTML remains 1 forever, why?

var a = 1;

$(addButton).click(function(){ //Once add button is clicked

a++;

console.log(a);


});

var fieldHTML = a;

Upvotes: 0

Views: 86

Answers (4)

Robert
Robert

Reputation: 190

var addButton = $("#btn");
var viewButton = $("#btn-2");
var a = 1;
var fieldHTML = a;

$(addButton).click(function() { 
  fieldHTML = increment();
  alert('a : ' + a);
});

$(viewButton).click(function() {
  alert('fieldHTML : '+fieldHTML);
});

function increment(){
   return ++a;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id='btn'>Inc a</button>
<button id='btn-2'>View fieldHTML</button>

Upvotes: -1

Robert
Robert

Reputation: 190

var addButton = $("#btn");
var viewButton = $("#btn-2");
var setButton = $("#btn-3");
var a = 1;
var fieldHTML = a; // on load, addign a value to fieldHTML variable  |  fieldHTML = 1

$(addButton).click(function() { //Inc by 1
  a++;
  console.log('a : '+a);
});

$(viewButton).click(function() {  //Show fieldHTML value in console
  console.log('fieldHTML : '+fieldHTML);
});

$(setButton).click(function() { // reassign a value to the fieldHTML variable  | on click event
  fieldHTML = a;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id='btn'>Inc a</button>
<button id='btn-3'>Set fieldHTML</button>
<button id='btn-2'>View fieldHTML</button>

Upvotes: -1

gavgrif
gavgrif

Reputation: 15489

You need to apply an id or class to the selector, wrap it into document ready, and also pass the new value of "a" to a function that can then manipulate the fieldHTML value. Check out the snippet note that I used alerts to demonstrate the increasing count rather thanconsole.log - simply because its in the snippet.

$(document).ready(function(){
     var a = 1;
      $('#addButton').click(function(){ //Once add button is clicked
       a++;
       alert("a = " + a);
       update_fieldHTML(a);
      });
  })

function update_fieldHTML(value){
var fieldHTML = value;
  alert("fieldHTML =" + fieldHTML);
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addButton">Click Me</button>

Upvotes: 0

Quentin
Quentin

Reputation: 943097

Because var fieldHTML = a; copies the value of a to fieldHTML.

It doesn't create a reference.

Changing the value of a (after you've set the value of fieldHTML) won't change the value of fieldHTML.

Upvotes: 4

Related Questions