使用复选框启用行内的选择选项

时间:2015-07-22 03:07:56

标签: jquery checkbox

如果在行中选中了复选框,请帮助我想启用带复选框的选项。代码仅在第一行内有效,但其余代码无效。我的复选框的ID是roomCheck,名称是chkbox

<table name = "mytab1" id = "MyTable" border = "1">
    <tr>
        <td><input type = "checkbox" name = "chkbox" id = "roomCheck"></td>
        <td><select id = "number" disabled><option>test</option></select>
    </tr>
    <tr>
        <td><input type = "checkbox" name = "chkbox"></td>
         <td><select id = "number" disabled><option>test</option></select>
    </tr>
    <tr>
        <td><input type = "checkbox" name = "chkbox" id = "roomCheck"></td>
        <td><select id = "number" disabled><option>test</option></select>
    </tr>
    <tr>
        <td><input type = "checkbox" name = "chkbox" id = "roomCheck"></td>
        <td><select id = "number" disabled><option>test</option></select>
    </tr>
    <tr>
        <td><input type = "checkbox" name = "chkbox" id = "roomCheck"></td>
        <td><select id = "number" disabled><option>test</option></select>
    </tr>
    <tr>
        <td><input type = "checkbox" name = "chkbox" id = "roomCheck"></td>
        <td><select id = "number" disabled><option>test</option></select>
    </tr>
</table>

<script src="jquery.min.js"></script>
<script language="JavaScript">
                          var update = function () {
                            if ($("#roomCheck").is(":checked")) {
                                $('#number').prop('disabled', false);
                            }
                            else {
                                $('#number').prop('disabled', 'disabled');
                            }       
                          };
                          $(update);
                          $("#roomCheck").change(update);
                        </script>
</script>

2 个答案:

答案 0 :(得分:-1)

当您使用 id 的选择器时,您必须始终为每个 ID 提供唯一名称,这是 html 基础知识,这就是为什么它只适用于第一行,下一行是无法识别的。

建议您阅读jquery selectors.

有很多方法可以实现您的目标,但您必须首先更改ID的命名,它们必须是唯一的,或者您可以通过使用 class 选择器来解决此问题。

答案 1 :(得分:-1)

这是我最终使用的代码修复了问题

$(document).ready(function() {
      // Disable select elements
      $('select').each(function() {
         $(this).attr("disabled","disabled");
      });

      // Enable them on click

       $("input[type=checkbox]").click(function(){
            if($(this).closest("tr").find("td").children("input[type=checkbox]").prop("checked"))
            {           
                $(this).closest("tr").find("td").children("select").removeAttr("disabled");
            }
            else
            {
                $(this).closest("tr").find("td").children("select").attr("disabled","disabled");
            }
       });
});