I want to enter five numbers into the array using one text box. And find the max number print it when I click the result button. I want to enter a number one by one when I clicked the add button it automatically add one by one to the array. HTML with JavaScript
var input = document.getElementById('input').value; function Add(numbers) { numbers = []; for(int x = 0; x < 5; x++) { var numbers = input[x]; } return numbers; } function findMax(arr) { var max = arr[0]; for(var i = 0; i < arr.length; i ++) { if(arr[i] > max) max = arr[i]; } return max; } function Result() { document.write(document.getElementById('demo').innerHTML = findMax(arr)) }
<p id = "demo">Print here the result</p> <input type = "text"; id = "input"> <button onclick = "Add()">Add</button> <button onclick = "Result()">Result</button>
To get all the 5 elements in an array using a single textbox, if they are seperated by single space do this:
var arr = input.split(' ');
This will create an array 'arr' with the numbers in it!
Actually there are many errors, that needs to be fixed, in the code you wrote:
numbers
array twice, inside your add
function, while you should be declaring it only once globally outside of it. input
value into the array
, just use .push()
. numbers
array after adding an element. document.write()
to show the result, just use document.getElementById('demo').innerHTML = findMax(numbers)
. numbers
array to your findMax()
function, instead of arr
in findMax(arr)
. Demo:
This is a demo with these errors corrected.
var input = document.getElementById('input'); var numbers = []; function Add() { if (numbers.length < 5) { numbers.push(+input.value); input.value = ""; } } function findMax(arr) { var max = arr[0]; for (var i = 1; i < arr.length; i++) { if (arr[i] > max) max = arr[i]; } return max; } function Result() { console.log(numbers); document.getElementById('demo').innerHTML = findMax(numbers); }
<p id="demo">Print here the result</p> <input type="text" ; id="input"> <button onclick="Add()">Add</button> <button onclick="Result()">Result</button>
You can try this code bellow :
<body>
<p id = "demo">Print here the result</p>
<input type = "text"; id = "input">
<button onclick = "Add()">Add</button>
<button onclick = "Result()">Result</button>
<script>
var numbers=[];
function Add() {
var input = document.getElementById('input').value;
if(input != ""){
numbers.push(parseFloat(input));
}
document.getElementById('input').value="";
console.log(numbers);
}
function Result() {
console.log(numbers);
document.getElementById('demo').innerHTML = Math.max.apply(null, numbers);;
}
</script>
</body>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.