2017-10-29 13 views
1

私はいくつかのテキストフィールドを持っています。入力フィールドの値をドロップダウンメニューに配置したいと思います。テキストが変更された場合は、ドロップダウンメニューを更新したいと思います。ここに私が得た最も近いものがあります。入力フィールドからテキストを取得し、ドロップダウンリストに挿入します

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ステートメント内で複数の組み合わせを試しましたが、何も私のために働いているようです。

私は間違って何をしていますか?あなたが提供できるあらゆるお手伝いをありがとうございました!

答えて

1

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>

+0

たとえば、ありがとうございました!私はまだ同じようにそれを得るために鉱山を調整しようとしている、私はどこかに何かが不足していると思うが、試し続けます。 :o)それを得ました!もう一度ありがとう! – Tina

+0

問題ありません!これであなたの質問が解決したら、それを答えとして受け入れてください、ありがとう! –

+0

間違いなく問題を解決しました。ありがとうございました。今日何か新しいことを学びました...ここで答えを受け入れる方法は、stackoverflowで。それを私の注意にも持ってくれてありがとう。 – Tina

関連する問題