我想通过 JSON 获取在页面加载时选择的选择选项值。
根据通过 ajax 传递的时间和时间进行加载,我将过滤轮类计时名称和 id 作为 JSON 结果。一切正常,但我不知道如何使 JSON 结果在 html 选择选项值中选择。
这是我选择的 HTML:
<select name="shift_name<%=index%>" id="shift_name<%=index%>" class="form-control"><option value="1">Morning Shift</option>
<option value="2">Evening Shift</option>
<option value="3">Night Shift</option>
<option value="4">Full Day Shift</option>
<option value="5">Full Night Shift</option></select>
这是我的 onload 函数,用于获取 select 的 JSON 结果值。
$(document).ready(function () {
var from_time = $('.from_time_<%=index%>').val();
var to_time = $('.to_time_<%=index%>').val();
$.ajax({
type: "GET",
url: "/employees/gate_passes/get_shift_timings",
dataType: "json",
data: {'from_time': from_time, 'to_time':to_time },
success: function(result){
for(term in result){
alert(result[term].id) #getting select option value to be selceted here
alert(result[term].name)
render = false;
//$('.select option[value="2"]').prop('selected', true);
//$('select#shift_time<%=i.index%> option[value="+result[term].id+"]').prop('selected', true);
}
}
})
});
我在一页中有 3 个选择。这样,基于该表单索引,选择的 id 和名称就会改变。在 JSON 结果中,我根据索引获得了适当的值。但我不知道如何在特定的选择选项中选择它。
您可以在我的 JSON 结果中看到注释部分,即为我的所有 3 个选择输入选择选项值,选择选项值为 2(即我的意思是我的所有选择输入都使用晚类名称进行选择)。但我的第二条注释行无法根据 id 和值工作。
最佳答案
将双引号更改为单引号。
$('select#shift_time<%=i.index%> option[value='+result[term].id+']').prop('selected', true);
使用双引号,您定义了一个字符串...因此您正在寻找值为 +value=result[term].id+
的 option
value="2"
。
关于javascript - 如何在页面加载时在 HTML 选择选项中选择 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61173677/