Reputation: 17
I am trying to get information from a textbox input. This textbox is meant to have numbers placed inside of it and will then be put into an array so that the numbers can be used to find the min, max, and average.
I am unsure of how to get the information from the textbox so I can use it to find the min, max, and average. I already have an idea of how to find the numbers, I just don't know how to collect them from the textbox.
Upvotes: 0
Views: 209
Reputation: 64
what I got from the question is how to retrieve data from the input form and then collect it into an array to be used in order to generate min, max, and average values. sorry if I misinterpreted, my english is not good.
you can get the value from form input using document.getElementById("id-input").value;
and you can split them then sort it with ascending.
I have example :
function cekValidasi() {
let inputNumber = document.getElementById("inputNumber").value;
let number = parseInt(inputNumber);
// here I split the input separated by commas
let splitNumber = inputNumber.split(",");
// here I sorting array to ascending
splitNumber.sort(function(a, b){return a-b});
// here checking form input
if (inputNumber == ""){
alert('Input is empty!');
}
else if (isNaN(number)){
alert('Must only input number')
}
else{
let min=0, max=0, average=0, sum=0;
for(let i=0; i<splitNumber.length; i++){
if(splitNumber[0]){
min = splitNumber[0];
}
if(splitNumber[splitNumber.length - 1]){
max = splitNumber[splitNumber.length - 1];
}
sum += parseInt(splitNumber[i]);
}
// you can manage digits after comma using toFixed()
average = (sum / splitNumber.length).toFixed(1);
let data = {
"min" : min,
"max" : max,
"average" : average
};
document.getElementById("min").innerHTML = data.min;
document.getElementById("max").innerHTML = data.max;
document.getElementById("average").innerHTML = data.average;
// empty input after used
document.getElementById('inputNumber').value = '';
}
}
<div style="margin-left: 20px; margin-top: 20px; width: 400px;">
<label> Input Number : </label><br>
<input type="text" name="inputNumber" id="inputNumber"
style="width: 97%; margin-bottom: 10px; padding: 5px" />
<br>
<button type="submit" name="calculate" id="calculate" style="float: right;"
onclick=cekValidasi()> Calculate </button>
<br><br>
<hr>
<br>
Min : <div id="min"></div>
Max : <div id="max"></div>
Average : <div id="average"></div>
</div>
Upvotes: 2