在jquery中更改另一列时启用一列

时间:2011-01-24 21:49:16

标签: jquery

表格中的我的行如下。

  <table>
    <tr>
    <td>Site1</td>
    <td>
    <select class="countryList"  
            name="countryList" 
            onchange="toggleVisibility(this);">
           <option value=""></option>
            <option value="country1" selected>country1</option>
            <option value="country2" >country2</option>
   </select>
  </td>
   <td>
    <select class="stateList"  
            name="stateList" 
            >
           <option value=""></option>
            <option value="state1" disabled>state1</option>
            <option value="state2" disabled>state2</option>
            <option value="state3" disabled>state3</option>

            </select>

   </td>
    </tr>
    <tr>
    <td>Site2</td>
<td>
    <select class="countryList"  
            name="countryList" 
            onchange="toggleVisibility(this);">
           <option value=""></option>
            <option value="country1" >country1</option>
            <option value="country2" selected>country2</option>
   </select>
  </td>
   <td>
    <select class="stateList"  
            name="stateList" 
            >
           <option value=""></option>
            <option value="state1" selected>state1</option>
            <option value="state2" >state2</option>
            <option value="state3" >state3</option>

            </select>

   </td>
    </tr>

    </table>

此处toggleVisibility方法应启用stateList的可见性。我写在下面。

function toggleVisibility(element){
                var country = $(element).attr("value");
                if(country == 'US'){
                    $(element).next().attr("disabled", false);
                    }else $(element).next().attr("disabled", true);
            }

但我收到$(element).next().attr未定义的javascript错误。请指出我的错误。给我一个关于JQuery表操作的好文档。非常感谢你的时间。

1 个答案:

答案 0 :(得分:0)

未定义$(element).next().attr(...)的原因是因为$(element).next()返回空的jQuery结果。 next()返回元素的下一个直接兄弟,在这种情况下没有。

您可以修改代码以直接选择stateList select

function toggleVisibility(element){
    var country = element.value;
    $("select[name='stateList']").attr("disabled", country == 'US');
}

更新:或者您可以更一般地在行中找到“下一个”选择:

function toggleVisibility(element){
    var country = element.value;
    $(element).closest("td").next().find("select").attr("disabled", country == 'US');
}

这会找到相邻的td select并禁用它。如果您想要更具体,可以使用select[name='stateList']代替。

我还删除了if/else块,转而将布尔表达式直接放在attr()的调用中。

附注:在表单元素上设置disabled属性不会切换可见性,它只是启用或禁用该表单字段上的用户输入。

如果您想根据countryList的值显示/隐藏表单字段,可以使用toggle

function toggleVisibility(element){
    var country = element.value;
    $("select[name='stateList']").toggle(country == 'US');
}