I am creating one drop down and in that dropdown I have a option called others, when others is selected, a new text box appear and user can enter any value. Now i want this entered value to be added to my drop down options. Till now I could implement the first half and i am now unable to add the new value back to my drop down.
function CheckColors(val){
var element=document.getElementById('popup');
if (val=='others') {
element.style.display='block';}
else {
element.style.display='none';
}
}
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option>10%</option>
<option>20%</option>
<option>30%</option>
<option>40%</option>
<option value="others" >others
</option>
<input type="button" name="button" value="Add"/>
</select>
<input type="text" id="popup" style='display:none;'/>
You would need to get the value that was added to the text box and create a new element to store in side the select
.
Here, I am using createElement to create a new option
when the user clicks add
. Then, I'm setting it's content using innerText
to what was added to the input.
I've done this when clicking the add
button but it could be used elsewhere. I've also added a check so we don't add an empty value as an option.
const CheckColors = (val) => {
const element = document.getElementById('popup')
if (val === 'others') {
element.style.display = 'block'
} else {
element.style.display = 'none'
}
}
const addBtn = document.querySelector('input[type="button"]')
// Add a listener for when the add button is clicked
addBtn.addEventListener('click', () => {
// get our dropdown and text box
const dropdown = document.getElementsByTagName('select')[0]
const element = document.getElementById('popup')
// Only add the value to the dropdown if it's not blank
if (element.value.length !== 0) {
// create the new option to add to our select
const option = document.createElement('option')
// Add the text that was in the text box
option.innerText = element.value
// Optionally give the option a value
option.value = 'something'
// Let's select this option too
option.selected = true
// Add the option to the select
dropdown.appendChild(option)
}
})
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option>10%</option>
<option>20%</option>
<option>30%</option>
<option>40%</option>
<option value="others" >others
</option>
<input type="button" name="button" value="Add"/>
</select>
<input type="text" id="popup" style='display:none;'/>