0

What am I doing wrong? If the button is clicked, variable s will have a value of 10, if not, it's 0. It's not working though.

$('button').observe('click', function () {
  var clicked = true;
  window.clicked = clicked;
});

if (clicked)
{
    var s = 10;
}
else 
{
    var s = 0; 
}

3 Answers 3

4

This might help you-

    <button>
    click
    </button>

<script>
       var clickCounter=0;
        var s=0;
        alert(s);
        $('button').on('click',function(){
          var s=10;
            alert(s);
            });
</script>

Initially the variable will store value of 0, after the vutton is clicked the variable is assigned with value of 10.

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

1 Comment

This worked for me, thanks. Although it didn't do as I wanted entirely because var s=10; inside the function needed to be without 'var'.
1

You are creating a variable S inside the if and else scope. Create a var s outside of the if and else and assign afterwards

Or you can do it like this:

   var s = 0;    
   $('button').observe('click', function () {
      s = 10;
   });

This way you assign 10 to s only after click. The code you had before would never set anything to 10

Comments

1

What exactly are you trying to achieve? Why don't you just set s = 10 on click event? Like this:

var s = 0;

$('button').click(function () {
  s = 10;
  console.log(s);
});

console.log(s);

Or, if you're trying to observe the value that changes, try something like this:

$('button').click(function () {
  object.s = 10;
});

var object = {};
Object.defineProperty(object, 's', {
  get: function() { 
    return this.value; 
  },
  set: function(newValue) {
    alert(newValue);
    this.value = newValue; 
  }
});

object.s = 0;

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.