Javascript没有设置选择的值(仅在有时)

时间:2018-06-05 19:56:03

标签: javascript jquery html

我有一个ajax请求,并且在成功时我试图将值设置为select,如下所示:

 $('#cadastro .ui-content #cpEstado').val(cadastro.IdentificadorEstado);
 alert(cadastro.IdentificadorEstado + ", " + $("#cpEstado").val());

就像我说它在请求的成功部分内,警报每次都带来cadastro.IdentificadorEstado的值,但是$(“#cpEstado”)。val()大部分时间都是null。以防我尝试将async设置为false失败。我也尝试使用

document.getElementById('cpEstado').value = cadastro.IdentificadorEstado;

但也没用。它可能是什么?

  <div class="ui-block-a uf">
       <label for="cpEstado" class="select">
             <select name="estado" id="cpEstado" data-theme="c">
                   <option value="" disabled selected>UF</option>
             </select>
       </label>
  </div>

Edit1:这是一个选择元素。

Edit2:当页面加载时,应该选择具有与请求和设置到select元素相同的值的选项。有时它被选中,有时它不被选中。

1 个答案:

答案 0 :(得分:2)

你需要这样做:

 $('#cadastro .ui-content #cpEstado').val(cadastro.IdentificadorEstado);
 $('#cadastro .ui-content #cpEstado').change();

或简写:

$('#cadastro .ui-content #cpEstado').val(cadastro.IdentificadorEstado).change();

你也不需要指定那个长选择器,如果元素有自己的id你可以直接通过id引用它,因为id在整个html文档中是唯一的,所以相反写作

$('#cadastro .ui-content #cpEstado')

你可以写

$('#cpEstado')

它应该有相同的结果,请注意,当选择器不是id而是其他一些

时,它会有不同的行为