jQuery 1.5中.val("value")无法按预期工作

3

我正在使用jQuery 1.5.2来操作表单上的两个下拉选择框。我的一个特殊要求是,如果选择了“其他”选项,则两个选择框都必须选择“其他”。

问题:

我的代码看起来像这样:

$("#Select_One")
    .change(function() {
        if($(this).val() == "Other") {
            $("#Select_Two").val("Other");
        }
        else {
            if($("#Select_Two").val() == "Other") {
                $("#Select_Two").val("");
            }
        }
    });

$("#Select_Two")
    .change(function() {
        if($(this).val() == "Other") {
            $("#Select_One").val("Other");
        }
        else {
            if($("#Select_One").val() == "Other") {
                $("#Select_One").val("");
            }
        }
    });

问题在于,$("#Select_Two").val("Other");并没有强制执行两个字段都为“其他”的规则,而是将#Select_Two下每个<option>value="Other"属性添加或覆盖。#Select_One同样存在相同的问题。此外,我的HTML来自Grails模板。
    <g:select id="Select_One"
              name="Units_One"
              class="Required DropDown"
              from="${Unit_One.values()}"
              optionKey="value_"
              optionValue="${{it.value_}}"
              noSelection="${['': message(code: 'units.no.selection')]}"
     />
     <g:select id="Select_Two"
               name="Units_Two"
               class="Required DropDown"
               from="${Unit_Two.values()}"
               optionKey="value_"
               optionValue="${{it.value_}}"
               noSelection="${['': message(code: 'units.no.selection')]}"
     />

在将以太网字段设置为“其他”后,Chrome调试器显示给我的内容如下...
<select name="Units_Two" id='Select_Two" class="Required DropDown">
  <option value="Other">Select Number</option>
  <option value="Other">Other</option>
  <option value="Other">1</option>
  etc...

这些函数的else子句的工作方式与预期的完全相同。

问题:

如何强制选择一个字段中的“其他”自动选择相应字段中的“其他”?


请检查这个 JSFiddle 并发布您的 HTML。看起来它工作得很好。 - Pointy
5
它的工作正常,请参见 http://jsfiddle.net/U75Rw/2/。我认为你遇到了其他问题。 - thecodeparadox
1
感谢大家的回复。我已经编辑了我的问题,包含更多的HTML代码。另外,感谢对jsfiddle的建议。我会将其加入我的工具集中。 - Rex Redi
你的Grails视图生成的HTML是否符合预期?如果是,那么你的javascript中的其他内容正在改变它。你发布的javascript不会更改选项元素的值属性。 - Milimetric
糟糕!我想我的缓存可能没有清除。现在我上面的代码完全按照预期工作了。不过我还有点困惑,因为在EI和Firefox上我一直得到错误的结果。再次感谢您的帮助。 - Rex Redi
1个回答

0
也许尝试一下:
$("#Select_One").change(function() {
    if ($(this).val() == "Other") {
        $("#Select_Two option[value='Other']").attr("selected",true);
    }
    else {
        if ($("#Select_Two").val() == "Other") {
            $("#Select_Two").val("");
        }
    }
});

$("#Select_Two").change(function() {
    if ($(this).val() == "Other") {
        $("#Select_One option[value='Other']").attr("selected",true);
    }
    else {
        if ($("#Select_One").val() == "Other") {
            $("#Select_One").val("");
        }
    }
});​

可能想要查看评论记录,问题已在昨天得到解决 :) - Dave Newton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接