'How to create an input field that accepts multiple comma separated pre-specified values?
I would like to create an input field that would create a drop-down list of available values when clicked. After that, the user can select one or more values and those will be added to the field, separated by commas (just like how we add the stackoverflow tags when asking a question). I can create a drop-down list like below, but it only allows me to select one single value at a time.
<div class="form-group">
<select class="form-control" name="year">
<option class="hidden" selected disabled>Please select your year</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
Solution 1:[1]
You can listen for change or click events on the select and construct a list of tokens based on what was clicked, or what's currently selected:
const s = document.querySelector('select');
const list = document.querySelector('ul');
s.addEventListener('change', e => {
list.innerHTML = [...e.target.selectedOptions].map(({value}) => `<li>${value}</li>`).join('');
})
:root {
font-family: sans-serif;
}
select {
min-width: 80px;
margin-bottom: 2rem;
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
}
li {
background: skyblue;
color: aliceblue;
border-radius: 4px;
padding: 0.5em 1em;
margin-right: 0.5em;
}
<select multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<ul></ul>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ray hatfield |
