【发布时间】:2020-07-25 04:09:21
【问题描述】:
我想通过 JSON 获取页面加载时选择的选择选项值。
基于不时通过 ajax 传递的负载,我将过滤换班时间名称和 ID 作为 JSON 结果。一切正常,但我不知道如何在 html 选择选项值中选择 JSON 结果。
这是我选择的 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 函数,用于获取选择的 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 和 name 将会改变。在 JSON 结果中,我根据我的索引获得了适当的值。但我不知道如何在特定的选择选项中选择它。
您可以在我的 JSON 结果中看到一个注释部分,即使用选择选项值 2 为我的所有 3 个选择输入选择选项值(即我的意思是我的所有选择输入都被选择为晚班名称)。但我的第二条评论行无法根据 id 和 value 工作。
【问题讨论】:
-
您是否尝试删除
result[term].id上的双引号和加号? -
$('#shift_name<%=index%>').val(result[term].id); -
谢谢@Hagai Wild。此代码正在运行。
标签: javascript jquery html ruby-on-rails json