簡體   English   中英

如何選擇文本輸入字段值並存儲到現有下拉列表中

[英]how to pick a text input field value and store into the existing drop down list

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. 現在我希望將此輸入的值添加到我的下拉選項中。 到目前為止,我可以實現前半部分,但我現在無法將新值添加回我的下拉列表中。


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;'/>

您需要獲取添加到文本框中的值並創建一個新元素以存儲在select中。

在這里,當用戶單擊add時,我使用createElement創建一個新option 然后,我使用innerText將其內容設置為添加到輸入中的內容。

單擊add按鈕時我已經這樣做了,但它可以在其他地方使用。 我還添加了一個檢查,因此我們不會添加空值作為選項。

 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;'/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM