簡體   English   中英

從輸入字段獲取文本並插入下拉列表

[英]Get text from input field and insert into dropdown list

我有幾個文本字段。 我想將輸入字段中的值放入下拉菜單中。 如果文本更改,我希望更新下拉菜單。 這是我得到的最接近的。

 function insertLab1() { var x = document.getElementById("insLabels"); var option1 = document.createElement("option"); var label1 = document.getElementById("lab1").value; option1.text = label1; x.add(option1, x[0]); if (label1 != option1.text){x.remove(x.options[0]);} } function insertLab2() { var x = document.getElementById("insLabels"); var option2 = document.createElement("option"); var label2 = document.getElementById("lab2").value; option2.text = label2; x.add(option2, x[1]); if (label2 != option2.text){x.remove(option2);} }
 Label 1 <input type="text" id="lab1" onchange="insertLab1()"><br> Label 2 <input type="text" id="lab2" onchange="insertLab2()"><br><br> Choose Label<br> <select id="insLabels"> </select>

標簽確實顯示在選項下拉列表中,但當標簽區域中的文本更改時,下拉值不會更改。 我在 if 語句中嘗試了多種組合,但似乎沒有任何效果對我有用。

關於我做錯了什么的任何想法? 非常感謝您提供的任何幫助!

如果不存在(第一次),您需要一種方法來獲取 lab1 和 lab2(如果存在)的現有選項,然后創建它並添加它。

如果它確實存在,那么您只需更新該值,而不是像您當前所做的那樣創建一個新的選項元素。

在下面的示例中,您可以看到我使用此代碼執行此操作。

  var option1 = document.getElementById("lab1Option");
  if (option1 == null) {
    option1 = document.createElement("option");
    option1.id = "lab1Option";
  }

 function insertLab1() { var x = document.getElementById("insLabels"); var option1 = document.getElementById("lab1Option"); if (option1 == null) { option1 = document.createElement("option"); option1.id = "lab1Option"; } var label1 = document.getElementById("lab1").value; option1.text = label1; x.add(option1, x[0]); if (label1 != option1.text) { x.remove(x.options[0]); } } function insertLab2() { var x = document.getElementById("insLabels"); var option2 = document.getElementById("lab2Option"); if (option2 == null) { option2 = document.createElement("option"); option2.id = "lab2Option"; } var label2 = document.getElementById("lab2").value; option2.text = label2; x.add(option2, x[1]); if (label2 != option2.text) { x.remove(option2); } }
 Label 1 <input type="text" id="lab1" onchange="insertLab1()"><br> Label 2 <input type="text" id="lab2" onchange="insertLab2()"><br><br> Choose Label<br> <select id="insLabels"> </select>

暫無
暫無

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

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