我正在尝试做点什么。我有以下代码段:
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']} - ${$additional['additional_price']}
<input type='number' name='additional_quantity' value='1' min='1' max='5'/>
<br/>";
}
echo "</form>";
我需要的是,当未选中名称为additional_id
的任何复选框时,其前面的名称为additional_quantity
的输入与其数量相关,将被禁用,反之亦然。但我不知道如何做到这一点,甚至更多,因为我需要使用foreach
。我可以用jQuery做到这一点吗?
答案 0 :(得分:1)
这将满足您的需求:
enable
disabled
属性添加到实际的html输入中,您需要在PHP代码中添加此属性name
如果您允许多个字段并且将提交表单,则他们都需要唯一的名称
$('.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;