jquery - 显示/隐藏基于所选单选按钮的复选框

时间:2011-05-05 08:34:02

标签: jquery jquery-selectors

我目前正在为订单流程开发一个小表单。

表单有多个字段,包括输入字段和单选按钮/复选框。

目前的表格如下:

    <form id="order_process" name="order_process" method="post" action="">
    <table>
    <tr>
       <td>
         <label for="colour">Colour</label>
      </td>
      <td>
        <label for="small">Small</label>
        <input type="radio" name="type" value="Small" />
      </td>
      <td>
        <input type="checkbox" name="colours" value="red" />
        <input type="checkbox" name="colours" value="blue" />
        <input type="checkbox" name="colours" value="yellow" />
      </td>
      <td>
        <label for="medium">Medium</label>
        <input type="radio" name="type" value="Medium" />
      </td>
      <td>
        <input type="checkbox" name="colours" value="orange" />
        <input type="checkbox" name="colours" value="blue" />
        <input type="checkbox" name="colours" value="green" />
      </td>
      <td>
        <label for="large">Large</label>
        <input type="radio" name="type" value="Large" />
      </td>
      <td>
        <input type="checkbox" name="colours" value="black" />
        <input type="checkbox" name="colours" value="white" />
        <input type="checkbox" name="colours" value="red" />
      </td>
   </tr>
   </table>
   </form>

我需要做的是,如果我选择一个特定的单选按钮,则只显示colours复选框。因此,这些复选框需要在页面加载时隐藏,并且仅基于所选的无线电显示。

我知道我可以使用jQuery实现这一点,但我不确定我是如何做到的。

非常感谢

3 个答案:

答案 0 :(得分:0)

首先隐藏包含复选框的行,之后您需要的是:

var lastRow = null;

$(":radio[name='type']").click(function(){
    if (lastRow != null){
       lastRow.toggle();
    }
    lastRow = $(this).parent().next();
    lastRow.toggle();
});

这将显示与其关联的复选框行。它还会隐藏任何以前打开的行,用于单击的其他单选按钮。

你可以在这里试试:

http://jsfiddle.net/jXrxW/

答案 1 :(得分:0)

使用jQuery有很多方法可以做到这一点,但重要的是你应该隐藏$('input type["checkbox"]')中的所有复选框($(document).ready),然后将click事件绑定到收音机按钮($('input type["radio"]')),显示相关项目。您可以通过在复选框中添加rel值来指明哪个单选按钮应该显示它们,从而轻松实现这一目标。

答案 2 :(得分:0)

另一种解决方案是在复选框中添加类,如下所示:

<td>
    <label for="small">Small</label>
    <input type="radio" name="type" value="Small" />
</td>
<td>
    <input type="checkbox" class="Small" name="colours" value="red" />
    <input type="checkbox" class="Small" name="colours" value="blue" />
    <input type="checkbox" class="Small" name="colours" value="yellow" />
</td>

然后,在您的单选按钮上添加change()侦听器,并show()相应的复选框:

$(":input[name=type]").change(function() {
    var value = $(this).val();
    $("input[type=checkbox]:not(." + value + ")").hide();
    $("input[type=checkbox]." + value).show();
});


jsFiddle example here

相关问题