将复选框与其他输入相关联

时间:2015-04-13 00:13:57

标签: javascript php jquery

我正在尝试做点什么。我有以下代码段:

echo "<form class='additionals'>";               
foreach($connection->query($sql2) as $additional)
{
    echo "<input class='additional-checkbox' type='checkbox' name='additional_id'
            value='{$additional['additional_id']}'/>
        {$additional['additional_name']} - &#36;{$additional['additional_price']}
        <input type='number' name='additional_quantity' value='1' min='1' max='5'/>
        <br/>";
}
echo "</form>";

我需要的是,当未选中名称为additional_id的任何复选框时,其前面的名称为additional_quantity的输入与其数量相关,将被禁用,反之亦然。但我不知道如何做到这一点,甚至更多,因为我需要使用foreach。我可以用jQuery做到这一点吗?

1 个答案:

答案 0 :(得分:1)

这将满足您的需求:

  • 请注意,我为复选框提供了课程enable
  • 我还将disabled属性添加到实际的html输入中,您需要在PHP代码中添加此属性
  • 我还为每个输入提供了唯一的name如果您允许多个字段并且将提交表单,则他们都需要唯一的名称

&#13;
&#13;
$('.enable').change(function(){
     var set =  $(this).is(':checked') ? false : true;      // ternary operator to test if the changed checkbox is now checked
     $(this).nextAll('input').first().attr('disabled',set); // find the next input and set it's disabled property according to the previous check  
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='additionals'>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id1' value='somevalue' />somevalue
  <input type='number' name='additional_quantity1' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id2' value='somevalue' />somevalue
  <input type='number' name='additional_quantity2' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id3' value='somevalue' />somevalue
  <input type='number' name='additional_quantity3' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id4' value='somevalue' />somevalue
  <input type='number' name='additional_quantity4' value='1' min='1' max='5' disabled/>
  <br/>
  <input class='additional-checkbox enable' type='checkbox' name='additional_id5' value='somevalue' />somevalue
  <input type='number' name='additional_quantity5' value='1' min='1' max='5' disabled/>
  <br/>
</form>
&#13;
&#13;
&#13;