This article will show you how to use the Math Object to figure out the absolute value of an input.
As a reminder, the absolute value of a number disregards the sign – it assumes that all numbers are 0 or greater and returns that number. To use the absolute value method of the Math Object, here’s the syntax:
Math.abs(inputVal);
Since we are using the Math Object, we start with Math. The absolute value method is the abbreviation abs. The set of parentheses invokes the method on the input value inside the parentheses and returns the absolute value.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <form onsubmit=handleSubmit(event)> <label for="absolute-value">Enter a number:</label> <input id="absolute-value" onchange=handleChange(event) type="text" name="absolute-value" value=""/> <input type="submit" value="Submit" /> </form> <h3 id="root"></h3> <script> let inputVal = "" const handleChange = e => { inputVal = e.target.value; console.log(inputVal) } const handleSubmit = e => { e.preventDefault(); const root = document.querySelector("#root"); root.innerHTML = Math.abs(inputVal); } const inputValue = document.getElementById("absolute-value").value </script> </body> </html>
If you were to enter in a string, it returns NaN. A null value would return 0, and positive or negative numbers would, of course, return the positive number.
Conclusion
That’s it! You can now use the Math object to figure out the absolute value of a number. Here’s some articles that can help you figure out what to learn next:
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.