javascript - 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:当页面加载时,应该选择与我随请求和设置到选择元素具有相同值的选项。有时会被选中,有时不会。
解决方案
你需要做:
$('#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 id
but some other
推荐阅读
- spring - 如何为 spring boot2 应用程序设置特定于环境的 log4j2 配置
- design-patterns - 用于确定对对象采取的操作的命令或审核集合
- javascript - 在 Chrome 隐身模式中未触发 onbeforeunload 事件
- ruby-on-rails - Rails ActiveStorage 从 URL 获取图像,然后在第一次点击时调整大小并上传
- c - 我正在尝试创建 ac 程序,该程序将不断从标准输入获取输入,直到输入退出
- javascript - 我在尝试运行“npx react-native run-android”时遇到错误
- r - 导入具有第一行特定单词的多个文本文件
- sql - 关于在SSIS包中向数据源和目标添加列的问题
- java - 将文本添加到pdf?
- python - 如何在 Python 中打印到 .txt 文件的下一行