0

I want to give max value to variable. The variable should not exceeds it's maximum value. I don't know how to do it. There is a javascript i created

var myvalue = 0
function click(){
  myvalue = myvalue + 10
  // I want to adjust max value for var myvalue that is 100.
  if (myvalue > 100){
  alert('this is max value')
  }
}

Please no JQuery. Only Javascript

4
  • Just to be clear, you want your variable to always stay within a range? Commented Aug 17, 2015 at 12:10
  • myvalue = 100; alert('this is max value'); Commented Aug 17, 2015 at 12:10
  • You know the Math.max, Math.min function?, maybe could serve you Commented Aug 17, 2015 at 12:11
  • 1
    Doesn't the code you've shown already do what you want, except within the if you would need to assign myvalue = 100;? Commented Aug 17, 2015 at 12:12

3 Answers 3

1

Asign the variable like this :

myValue = myValue < 100 ? myValue : 100;
Sign up to request clarification or add additional context in comments.

Comments

0

Although I'm not sure where you're going to take the variable, you could use "Math.min" to avoid the variable is greater than a number

var myvalue = 0
function click(){
    myvalue = myvalue + 10;
    myvalue = Math.min(myvalue, 100);
}

//Another examples
var foo = Math.min(35,100) //35
var foo = Math.min(545,100) //100
var foo = Math.min(125,100) //100
var foo = Math.min(12,100) //12

Comments

0

put the statement which updates the value of your variable inside an if

var myvalue = 0;
function click() {
  if (myvalue < 100) {
    myvalue = myvalue + 10;
  }
  else {
    alert('this is max value');
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.