【问题标题】:Dynamically generated select tag option not filtered by jquery动态生成的选择标签选项未被 jquery 过滤
【发布时间】:2014-11-12 11:47:36
【问题描述】:

我使用jstl 动态生成选择标签,如下所示。但我未能在 jquery 中选择选项。

JSP:

<c:forEach var="p" items="${model.multiphase}" varStatus="row">
    <select class="form-control status" name="status">
        <option value="Notyetstarted">Not Yet Started</option>
        <option value="Inprogress">InProgress</option>
        <option value="Onhold">OnHold</option>
        <option value="Closed">Closed</option>
    </select>
    <input type="hidden" id="upstatus_${row.index}" value="<c:out value='${p.getProjectPhase().getPhaseStatus()}'/>" />
</c:forEach>

上面的jstl生成下面的html

<select class="form-control status" name="status">
        <option value="Notyetstarted">Not Yet Started</option>
        <option value="Inprogress">InProgress</option>
        <option value="Onhold">OnHold</option>
        <option value="Closed">Closed</option>
    </select>
    <input type="hidden" id="upstatus_0" value="Closed" />
 <select class="form-control status" name="status">
        <option value="Notyetstarted">Not Yet Started</option>
        <option value="Inprogress">InProgress</option>
        <option value="Onhold">OnHold</option>
        <option value="Closed">Closed</option>
    </select>
    <input type="hidden" id="upstatus_1" value="Onhold" />

我使用下面的 jquery 来选择选项。

$(".status option").each(function () {
    alert("fd");

    $(this).find("option").filter(function () {

        return $(this).val() == $("#upstatus_" + index).val();

    }).prop('selected', true);
});

如何预选值? 任何帮助将不胜感激!!!

【问题讨论】:

  • 这应该可以工作:$("option",'select.status').filter(function () { return $(this).val() == $("#upstatus_" + index).val(); }).prop('selected', true);
  • @ventkata,没用,我有动态选择标签
  • 您可能有其他问题,请尝试不区分大小写$("option",'select.status').filter(function () { return $(this).val().toLowerCase() == $("#upstatus_" + index).val().toLowerCase(); }).prop('selected', true); 还要检查您使用的索引是否正确

标签: java javascript jquery jstl


【解决方案1】:

改成这样:

$(".status").each(function () {
    var that = $(this);
    $(this).find('option').filter(function (index) {
        console.log($(this).parent().next(":hidden").val());
        return $(this).val() === that.next(":hidden").val()
    }).prop('selected', true);
});

Sample Demo

Updated Sample Demo


-&gt; : jquery 没有进入警报。

因为你有.each() 迭代不是在选择元素上的选项。


虽然你也可以改成这样:

$(".status").each(function (i) { // add a index "i" here
    $(this).find('option').filter(function () {
        return $(this).val() === $("#upstatus_"+i).val() // use that here
    }).prop('selected', true);
});

Sample for this.

【讨论】:

  • 不工作我在脚本 $(".status").each(function(index){alert("Dds");} 中添加了以下代码,但未触发警报
  • ,为第一行工作,但其他行无法预选
  • 您的示例只有一个选择,但我有更多选择标签
  • 很高兴这对您有用,但无论如何,如果您的标记被更改,那么第一个使用 .next() 方法的标记将失败,因此在这种情况下,您可以查看下面的新标记更新小提琴。
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
相关资源
最近更新 更多