[英]Default Select Option Based on Input Value
I have the following select
on my form 我在表格上有以下
select
<select id="select-1">
<option value="11">Option 11</option>
<option value="12">Option 12</option>
<option value="13">Option 13</option>
</select>
And a hidden input 和隐藏的输入
<input id="hidden-input-1" value="13">
When my page loads, hidden-input-1
could have a value of either 11, 12, or 13. I'd like to default my select to whatever the value of this input might be. 当页面加载时,
hidden-input-1
的值可以为11、12或13。我想将我的选择默认为该输入的值。 So far I've tried to set this using .val(): 到目前为止,我尝试使用.val()进行设置:
$( document ).ready(function() {
/*...
do AJAX stuff to set input value
...*/
$("#select-1").val($("#hidden-input-1").val());
});
Which just returns a blank selection. 只是返回一个空白选择。 Any ideas on how to nail this?
关于如何确定这一点的任何想法?
You are trying to access the elements when they are not loaded into DOM, so you are not getting any value, Below the correct way to do. 当元素未加载到DOM中时,您正在尝试访问它们,因此您没有获得任何值,这是正确的方法。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="select-1"> <option value="11">Option 11</option> <option value="12">Option 12</option> <option value="13">Option 13</option> </select> <input id="hidden-input-1" value="13"> <script> $(document).ready(function() { $("#select-1").val($("#hidden-input-1").val()); }); </script>
/*... do AJAX stuff to set input value ...*/
$.ajax()
is asynchronous ; $.ajax()
是异步的; $("#select-1").val($("#hidden-input-1").val());
appear synchronous , could be called before $.ajax()
completes setting hidden input
value ? 似乎同步,可以在
$.ajax()
完成设置隐藏input
值之前$.ajax()
吗? if outside of , following $.ajax()
success , error callbacks. 如果在
$.ajax()
成功之后,则返回错误回调。
Try calling $("#select-1").val($("#hidden-input-1").val());
尝试调用
$("#select-1").val($("#hidden-input-1").val());
at complete handler of ajax call 在完整的ajax调用处理程序中
$.ajax().then(function() {
/*...
do AJAX stuff to set input value
...*/
// set `select` value when `input` value set
$("#select-1").val($("#hidden-input-1").val());
}, function err(jqxhr) {
console.log(jqxhr.status)
})
` `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.