0

Here is my function i am declaring bar='0' i just want to update the value of bar='1' only if change is clicked, else the bar should have the default value as 0. so that when ever i alert the bar should alert.

i.e.,

If i click on the change the bar should have the value of 1 else it should have the default value as 0

How can i do this ..

Here is the code i have tried so far

<script>
$(function(){
      var bar = "0";
      $('#change').click(function()
      {
      var bar = "1";
      });
      $('#fire').click(function()
      alert(bar);
      }
});
</script>
2
  • is 'change' an id or a class? the same question goes to 'action'. and can you provide your html markup. Commented Feb 25, 2015 at 19:41
  • i have updated it's change and fire id Commented Feb 25, 2015 at 19:43

1 Answer 1

4

The second time around, in the click handler, you shouldn't use var, as that would redeclare bar within the function scope of the click handler.

Simply remove the var as such:

$(function(){
  var bar = "0";
  $('change').click(function()
  {
    bar = "1"; // Remove `var`
  });
  $('action').click(function(){
    alert(bar);
  }
});

This is thanks to javascript's support for closures. I really recommend reading the closure bit (and rest) of Eloquent Javascript, available here: http://eloquentjavascript.net/03_functions.html

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

2 Comments

Glad to help. Give that page a read if you have time – you'll enjoy javascript more by doing it!
sure do :) i will do it now itself

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.