将选择值更改为动态添加的选项会导致值=“”

时间:2016-04-12 20:15:26

标签: javascript ajax

我有select我无法以编程方式更改。 select仅以option开头:

初始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.

我尝试将options硬编码到select中,并按预期工作。动态添加它们似乎是个问题。我可以提出一个解决方法,但有人可以解释为什么会发生这种情况吗?

2 个答案:

答案 0 :(得分:2)

您正在使用AJAX加载选项,这是异步的。在分配给.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);
    });
  }

答案 1 :(得分:0)

您不必设置<select>字段的值,但是您应该将属性selected分配给您要选择的option字段。< / p>

请参阅here