【问题标题】:Jquery : Setting selected state on select option items populated via ajaxJquery:在通过 ajax 填充的选择选项项目上设置选定状态
【发布时间】:2011-11-04 19:02:27
【问题描述】:

我有 6 个选择框 (sbs),每行 3 个,所以两行。前三个 sbs 包含通过 php 填充的选项列表,数据从 mysql 拉回。当从每个框中选择一个选项时,我正在使用 jquery(通过 ajax)来拉回紧接其下方的 sb 的选项项,并用相应的数据填充所述 sb。我单击“创建”,数据通过 ajax 发送到 php 脚本,然后将数据存储在表格中,并在表格下方的表格中返回提交的下拉数据(尽管已格式化)。因此,在创建“组合”之后,您可能会得到类似这样的东西。冒号左边的每一个都是选择框顶行上的一个选项,然后您从下面显示的相应框中选择了选项。

Color: Red    |   Capacity : 4GB    |      Model : ABC    |    EDIT
Color: Blue   |       Speed: 2GHZ   |   Capacity : 2GB    |    EDIT

等等

如果我想编辑记录,我单击编辑,jquery 找到单击的编辑按钮的 id,通过 ajax 将其传递给另一个 php 脚本,然后返回一个带有相关数据的 json 对象,然后用于重新填充带有所选选项的下拉框。到目前为止一切正常。

我的问题是,只有顶行 sbs 在单击编辑时获得选择的选项之一。子选项没有被选中,我不知道为什么。我可以获得正确的显示选项,但无法为我的 json 对象中返回的任何匹配值设置选定状态。我已经花了 8 个小时试图弄清楚并在 SOverflow 和其他网站上尝试了各种方法,但都没有奏效 - 老实说,我对 javascript/ajax 的经验并不丰富。

在成功的 ajax 进程即成功:我正在执行以下操作:

var jObj = $.parseJSON(html);

//parentVariations# is the select boxes in the top row where 
//Color, capacity, model options are displayed.
//The trigger fires off my ajax function which is responsible for 
//populating the corresponding child select box with relevant data.

$('#parentVariations1').val(jObj.groupAttr1).trigger('change'); 
$('#parentVariations2').val(jObj.groupAttr2).trigger('change'); 
$('#parentVariations3').val(jObj.groupAttr3).trigger('change'); 

//childVariations# is the child option box, i have the same code for each child
//box but am only showing the first one here for simplicitys sake.
//What I thought I was doing here is getting each option then if the value 
//matches that held in my corresponding json object set that option to selected...
//Doesn't work :'(
$("#childVariations1 option").each(function()
{
if($(this).val() == jObj.childAttr1)
{
      $("#childVariations1 option").attr('selected','selected');
}
});

任何帮助都会非常受欢迎,因为它把我逼到了边缘。

【问题讨论】:

    标签: php jquery ajax jquery-selectbox


    【解决方案1】:

    $("#childVariations1 option") 是所有选项的数组。您需要指定哪一个:

    $("#childVariations1 option").eq(1).attr('selected','selected');
    

    如果您的情况,使用for 循环并使用索引来获取当前位置,而不是使用.each。 (或设置一个计数器)

    【讨论】:

    • 感谢您的帮助 Diodeus,我相信您的解决方案有效,但我认为某些东西正在覆盖所选状态。如果我反复快速地单击编辑按钮,我可以看到选择框正在使用正确选择的项目进行更新,但随后它会被框中的第一个选项“请选择”覆盖。我注意到如果我添加一个 alert('');在 for 循环之前,一切正常。
    • 尝试在jsfiddle.net上发布你的代码,我会看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2020-04-01
    • 1970-01-01
    • 2018-06-28
    • 2012-12-04
    相关资源
    最近更新 更多