【问题标题】:How to make the JSON result as selected in HTML select option on page load如何在页面加载时在 HTML 选择选项中选择 JSON 结果
【发布时间】: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&lt;%=index%&gt;').val(result[term].id);
  • 谢谢@Hagai Wild。此代码正在运行。

标签: javascript jquery html ruby-on-rails json


【解决方案1】:

将双引号改为单引号。

$('select#shift_time<%=i.index%> option[value='+result[term].id+']').prop('selected', true);

使用双引号,您定义了一个字符串...所以您在哪里寻找值为+value=result[term].id+ 而不是value="2"option

【讨论】:

  • 感谢@Louys Patrice Bessette 我这样修改了你的代码。 $('select#shift_time option[value='+result[term].id+']').prop('selected', true);它正在工作
猜你喜欢
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-12
  • 1970-01-01
  • 2011-01-18
相关资源
最近更新 更多