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

Asked

Viewed 242 times

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.
How can I do that? I only have 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>
  • Related: https://answall.com/questions/92187/como-addir-option-para-um-select-por-jquery-javascript

1 answer

2


You can do it like this, I’ll check if there’s anything typed in here so you don’t add a <option> text-less:

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 be:

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>

Heed, as explained in the link this last alternative does not work in IE <= V9 nor in safari

  • very good! but there is some way to make the box combo itself digitize without needing another input like text?

  • @rayraisemeup, which is the combo box, can show which html element is that sff

  • combo box is the same as <select>.. the check box with an arrow that when clicking shows the options. It has how to make this element digitized?

  • I added an @rayraisemeup alternative, that could be it?

  • Yes! Works very well, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.