.val(“value”)在jQuery 1.5中没有按预期工作

时间:2012-06-13 17:09:20

标签: javascript jquery grails jquery-1.5

我正在使用jQuery 1.5.2来操作表单上的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");不是强制执行两个字段都为“其他”的规则,而只是在value="Other"下的<option>下添加或覆盖#Select_Two属性。 }。 #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子句正如预期的那样工作。


问题:

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

1 个答案:

答案 0 :(得分: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("");
        }
    }
});​