我通过$(document).ready();
函数内的ajax调用渲染选择框的所有选项。
我在页面顶部有一个php变量,初始化为1,如
$expert_id = 1;
现在这是我的代码
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
}
});
});
在将所有选项附加到我的专家选择框时,我想检查data[i].expert_id
是否等于我的php变量,如果它等于我的php变量那么它应该被选中。
任何人都可以帮我这个吗?
答案 0 :(得分:1)
在创建
selected
对象(jQuery
)时使用<option>
属性/属性
参考jQuery( html [, ownerDocument ] )
var data = [{
expert_id: 1,
expert_name: 'rayon'
}, {
expert_id: 2,
expert_name: 'bye'
}];
var expert_id = 2;
$.each(data, function(i, item) {
$('#expert').append($('<option>', {
value: data[i].expert_id,
text: data[i].expert_name,
selected: expert_id === data[i].expert_id
}));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="expert"></select>
&#13;
答案 1 :(得分:1)
你试过这样的事吗:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
}));
});
var expert_id = '<?php echo $expert_id ; ?>';
$('#expert').val(expert_id); //setting the value of select box
}
});
});
答案 2 :(得分:0)
定义在顶部:
<span id="foo"><?php echo $expert_id; ?></span>
添加脚本
<script>
$(document).ready(function(){
$.ajax({
type: "POST",
url: "<?php echo base_url('insoadmin/experts/all_experts');?>",
dataType: "json",
success: function(data, page) {
$.each(data, function(i, item) {
//console.log(data[i].expert_name);
$('#expert').append($('<option>', {
value: data[i].expert_id,
text : data[i].expert_name,
var foo=$('#foo').html();
if(foo==data[i].expert_id){
//do something
}
}));
});
}
});
});
</script>