JavaScript: Get values of a multiple select box
5 February 2023 (Updated 5 February 2023)
<!DOCTYPE html>
<html>
<head>
<title>JavaScript: Get values of a multiple select box</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="location">Select location (hold shift and select)</label> <br />
<select name="location" id="location" multiple>
<option value="">Anywhere</option>
<option value="london">London</option>
<option value="manchester">Manchester</option>
<option value="birmingham">Birmingham</option>
</select>
<div id="output" style="margin-top: 30px;" ;></div>
<script>
document
.querySelector('#location')
.addEventListener('change', (event) => {
const selectedValues = [...event.target.options]
.filter((option) => option.selected)
.map((option) => option.value)
document.querySelector('#output').innerText = selectedValues.join(
', '
)
})
</script>
</body>
</html>
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment