How to limit values for oninput calculation without limiting the input values?

How can one limit the output values, say, from 5 to 195. without limiting the input values?

<!DOCTYPE html>
<html>
<body>

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0
<input type="range" id="a" value="50">100 +
<input type="number" id="b" value="50">=
<output name="x" for="a b"></output>
</form>

</body>
</html>

Answers


<!DOCTYPE html>
<html>
<body>

<form oninput="var n = parseInt(a.value)+parseInt(b.value); x.value =  n < 5 ? 5 : ( n > 195 ? 195 : n);">0
<input type="range" id="a" value="50">100 +
<input type="number" id="b" value="50">=
<output name="x" for="a b"></output>
</form>

</body>
</html>

This uses a nested trinary opertor a ? b : c which is essentially a if b else c. When it's nested you can think of it like this: a ? b : (c ? d : e) as a if b ELSE (c if d else e) as the result of (c ? d : e) is the equivalent of c in a ? b : c.

Try it out here

Alternativley, you could do

<form oninput="x.value = Math.min(Math.max(5,parseInt(a.value)+parseInt(b.value)),195);"/>

Which achieves the same result, just in a different way, you can play with it here

Try it out here: JSfiddle


Need Your Help

update 2 different table with just 1 button in asp.net

asp.net sql visual-studio button

I'm trying to update 2 different table with 1 button in my web application. I'm currently using asp.net to develop my web app. I wonder if it is possible to update 2 different columns from 2 differ...

Writing a highly performant Cache

java caching optimization memory concurrenthashmap

I wrote a stock market simulator which uses a ConcurrentHashMap as a cache.