Ad

Min Max Value In Javascript, No Errors Showing, But Code Doesn't Work

- 1 answer

I'm really new to this, no errors are showing up, but code doesn't work. Trying to get the min and max value of numbers entered in the text-box.

here's the code:

<html lang="en">

<body>
  <h1>Problem JavaScript</h1>
  Enter a series of numbers with spaces in between each:
  <input type="text" name="qty1" id="qty"/>
  <button type="button" onclick="calculate();">Enter</button>
</body>
</html

function calculate(){

var numInput = getElementById("qty");
var numArray = numInput.split(" ");

document.write('Min value is:', Math.min.apply(null, numArray));
document.write('Max value is:', Math.max.apply(null, numArray));
}
Ad

Answer

You almost got it.

1.) getElementById should be document.getElementById. See document.getElementById() VS. getElementById()

2.) Calling .split on the element returned by getElementById isn't going to work, you need to do that to the element's value. ie:

var numInput = document.getElementById("qty").value;
var numArray = numInput.split(" ");

Here's a full example

function calculate() {
  var numInput = document.getElementById("qty").value;
  var numArray = numInput.split(" ");

  document.write('Min value is:', Math.min.apply(null, numArray));
  document.write('Max value is:', Math.max.apply(null, numArray));
}
<h1> Problem JavaScript</h1> Enter a series of numbers with spaces in between each:
<input type="text" id="qty">
<input type="button" id="go" value="Go" onclick="calculate()">

Ad
source: stackoverflow.com
Ad