在html的select和option中的文本框中添加新值

时间:2017-10-24 19:17:54

标签: html-select

我在html页面中的select类型中有一些下拉值。我想通过文本框从用户添加一些额外的值。当用户输入值并按下按钮时,该值应添加到下拉选择框中。

<table>
  <tr>
    <td> Blood Test: </td>
    <td>
      <select name="DragCompany"> 
        <option value="ACI Ltd.">ACI</option>
        <option value="Apollo Pharmaceutical Laboratories Ltd.">Appolo</option> 
        <option value="Beximco Pharmaceuticals Ltd">Beximco</option> 
        <option value="Beacon Pharmaceuticals Limit">Beacon</option> 
        <option value="Delta Pharma Limited">Delta</option> 
        <option value="Globe Pharmaceuticals Ltd">Globe</option> 
      </select>
    </td>
  </tr>
</table>

1 个答案:

答案 0 :(得分:0)

试试这个:

var s = document.getElementById('DragCompany');
var inputContainer = document.getElementById('newinput');

function addtoselect() {
  if (inputContainer.value) {
    s.options[s.options.length] = new Option(inputContainer.value);
    inputContainer.value = '';
  }
}
<table>
  <tr>
    <td> Blood Test: </td>
    <td>
      <select id="DragCompany" name="DragCompany"> 
        <option value="ACI Ltd.">ACI</option>
        <option value="Apollo Pharmaceutical Laboratories Ltd.">Appolo</option> 
        <option value="Beximco Pharmaceuticals Ltd">Beximco</option> 
        <option value="Beacon Pharmaceuticals Limit">Beacon</option> 
        <option value="Delta Pharma Limited">Delta</option> 
        <option value="Globe Pharmaceuticals Ltd">Globe</option> 
      </select>
    </td>
  </tr>
</table>

<input type="text" id="newinput">
<button onclick="addtoselect()">Add</button>