0

For example, I have the function isPercentage, that uses a value defined in whatever function in which isPercentage is called:

isPercentage=function(){
        if (value<1){
            value=value*100;
            console.log(value);             
            $(this).val(value);
        }else if(value>100){
            value=value/100;
            $(this).val(value);
        }       
}



$("#userDiscount").change(function(){
        var value=$(this).val();
        isPercentage(); 
});

However, when a change occurs on $("#userDiscount"), I get a "value is not defined" error. How do I define "value" in such a way that isPercentage() can then pick it up.

Thanks!

1
  • JavaScript has lexical scope. What you are trying to do would involve dynamic scope, which none of the popular languages implements. Commented May 18, 2016 at 16:07

2 Answers 2

4

When you call a function, it executes in its own context. This means that when isPercentage() is called, the this value inside is different than outside that function.

isPercentage() has no idea what value is (since it's out of scope) and this is not what you think it is. You need to tell that function what those values are.

First off, you should pass value as a parameter to isPercentage so it can use that value. Second, you should have it return a value so you can set $(this).val().

var isPercentage = function(value){
    if (value<1){
        value = value*100;
    } else if(value>100){
        value = value/100;
    }       
    return value;
};

$("#userDiscount").change(function(){
    var value = $(this).val();
    value = isPercentage(value);
    $(this).val(value);
});
Sign up to request clarification or add additional context in comments.

Comments

0

I might do it slightly differently to Rocket by capturing the actual element inside the function instead. I'd probably change the name of the function so that it made sense in this context.

function processValue(e) {
  var element = e.currentTarget;
  var value = $(element).val();
  if (value < 1) {
    value = value * 100;
    $(element).val(value);
  } else if (value > 100) {
    value = value / 100;
    $(element).val(value);
  }
}

$("#userDiscount").on('change', processValue);

DEMO

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.