Skip to content

Instantly share code, notes, and snippets.

@jkcox
Created February 9, 2022 19:51
Show Gist options
  • Save jkcox/3953d051a5b61c1a632ad221d3a9f70b to your computer and use it in GitHub Desktop.
Save jkcox/3953d051a5b61c1a632ad221d3a9f70b to your computer and use it in GitHub Desktop.
Form input JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>form</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<div class="container border rounded m-3">
<h1>form</h1>
<form id="math-form">
<div class="form-text">Calculate the average and median of three positive integers using the inputs below.</div>
<div class="m-3">
<label for="input1" class="form-label">Input 1</label>
<input type="number" min="1" class="form-control" id="input1" name="input1">
</div>
<div class="m-3">
<label for="input2" class="form-label">Input 2</label>
<input type="number" min="1" class="form-control" id="input2" name="input2">
</div>
<div class="m-3">
<label for="input3" class="form-label">Input 3</label>
<input type="number" min="1" class="form-control" id="input3" name="input3">
</div>
<div class="m-3">
<button type="submit" class="btn btn-primary">Calculate values</button>
</div>
</form>
</div>
<div class="container border rounded m-3">
<h2>Results</h2>
<h4>Average: <span id="averageContainer"></span></h4>
<h4>Median: <span id="medianContainer"></span></h4>
</div>
<script>
const form = document.getElementById('math-form')
form.addEventListener('submit', (event) => {
event.preventDefault()
//filter out unwanted elements, push user input to array, cast object string to number
let inputArray = []
for (let i = 0; i < form.elements.length; i++) {
if (form.elements[i].type !== 'submit') {
let userInput = form.elements[i].value
inputArray.push(Number(userInput))
}
}
//calculate average
const sumInput = (sum, num) => sum + num
let average = (inputArray.reduce(sumInput)) / (inputArray.length)
//calculate median for 3 inputs
const sortInput = (a, b) => a - b
let medianSortArray = inputArray.sort(sortInput)
median = medianSortArray[1]
//display values to user
document.getElementById('averageContainer').innerHTML = average
document.getElementById('medianContainer').innerHTML = median
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment