2016-04-12 13 views
0

プログラムで変更できないselectがあります。一つだけoptionselect開始:動的に追加されたオプションに選択値を変更すると、値= ""が発生する

初期HTML:

<select id="clients" name="client"> 
    <option>Existing Clients...</option> 
    </select> 

は、その後、私はクライアントを取得し、selectに追加:

getClients(); 

function getClients() { 
    $.get('ajax/get-clients.php') 
    .done(function(response) { 
     for (let client of JSON.parse(response)) { 
     addClientOption(client.id, client.company_name); 
     } 
    }) 
    .fail(function(response) { 
     console.log(response); 
    }); 
    } 

function addClientOption(id, name) { 
    let newOption = document.createElement('option'); 

    newOption.value = parseInt(id); 
    newOption.text = name; 
    document.getElementById('clients').appendChild(newOption); 
} 

を今ではいくつかのオプションを持っています

<select id="clients" name="client"> 
    <option>Existing Clients...</option> 
    <option value="6">Number1</option> 
    <option value="77">SecondROUND</option> 
    <option value="14">Whips Dat Llama</option> 
</select> 

私はその値を変更しようとしています:

console.log(document.getElementById('clients').value); // =>"Existing Clients..." 
document.getElementById('clients').value = 6;   // expecting "Number1" 
console.log(document.getElementById('clients').value); // =>"" 

// And the select still shows the "Existing Clients..." option. 

私はselectoptionsをハードコーディングしようと、期待どおりに動作します。それらを動的に追加することが問題と思われます。私は回避策を考え出すことができますが、誰かがなぜこれが起こっているのか説明できますか?

+0

それは私の作品:https://jsfiddle.net/barmar/3ekvaxxr/3/ – Barmar

+0

は、あなたが 'AJAXの応答が受信された後.value'に代入していますか?コード内のその割り当てはどこですか? – Barmar

+0

こんにちは、Barmar、フィドルのおかげで。代入はgetClients()の呼び出しの直後です。 '$(function(){getClients(); document.getElementById( 'clients')。value = 6;});' – Rhono

答えて

2

を参照してください。 .valueに割り当てる前に応答を待たなければなりません。そうしないと、その値のオプションは存在しません。だから、getClientsコールバック関数で行う必要があります。

function getClients() { 
    $.get('ajax/get-clients.php') 
    .done(function(response) { 
     for (let client of JSON.parse(response)) { 
     addClientOption(client.id, client.company_name); 
     } 
     document.getElementById('clients').value = 6; 
    }) 
    .fail(function(response) { 
     console.log(response); 
    }); 
    } 
+0

AJAXが終了する前に次の命令(.valueの代入)に進みますか?もちろんOooooooh。それはAJAXの仕組みだからです。 Ha。助けてくれてありがとう。 – Rhono

0

<select> -fieldの値を設定する必要はありませんが、選択するフィールドには、selectedという属性を割り当てる必要があります。

はあなたが非同期でAJAXを使用して、オプションをロードしているhere

+0

'