首页 > 解决方案 > Javascript未设置选择的值(仅有时)

问题描述

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

 $('#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:当页面加载时,应该选择与我随请求和设置到选择元素具有相同值的选项。有时会被选中,有时不会。

标签: javascriptjqueryhtml

解决方案


你需要做:

 $('#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')

and it should have same result, note that it will have different behavior when selector isn't idbut some other


推荐阅读