How to allow the user to add a new option in a select?

0

I need to mount a select where the user can add new options, so I need the select to allow typing and a button next to it would call the function to include in the list. Home How can I do this? I have just the basic select with the link that should work as a button:

<select class="tags" name="abrangencia" style="width: 300px;">
    <option value="">opt 1</option>
    <option value="">opt 2</option>
    <option value="">opt 3</option>
    <option value="">opt 4</option>
</select>
<a>
   <img style="height: 38px; margin: -10px;" src="imagens/campanha/botao-mais.jpg">
</a>
    
asked by anonymous 14.09.2017 / 17:04

1 answer

2

You can do this, here I check if there is something typed so you do not add a <option> without text:

var input_ele = document.getElementById('new-opt');
var add_btn = document.getElementById('add-btn');
var sel_opts = document.getElementById('sel-opts');
var input_val;
add_btn.addEventListener('click', function() {
  input_val = input_ele.value;
  if(input_val.trim() != '') {
    sel_opts.innerHTML += '<option>' +input_val+ '</option>';
    input_ele.value = '';
  }
});
<input id="new-opt"/>
<button id="add-btn">Adicionar opção</button>
<select id="sel-opts">
  <option>Eu já existo</option>
</select>

With datalist would read:

var input_ele = document.getElementById('new-opt');
var add_btn = document.getElementById('add-btn');
var sel_opts = document.getElementById('sel-opts');
var input_val;
add_btn.addEventListener('click', function() {
  input_val = input_ele.value;
  if(input_val.trim() != '') {
    sel_opts.innerHTML += '<option>' +input_val+ '</option>';
    input_ele.value = '';
  }
});
<input list="sel-opts" id="new-opt"/>
<button id="add-btn">Adicionar opção</button>
<datalist id="sel-opts">
  <option>Eu já existo</option>
</datalist>

Warning , as explained in the link this last alternative does not work in IE

14.09.2017 / 17:12