query($sql2) as $additional) { ec-6ren">
gpt4 book ai didi

javascript - 将复选框与另一个输入相关联

转载 作者:行者123 更新时间:2023-11-30 00:30:46 26 4
gpt4 key购买 nike

我正在尝试做某事。我有以下代码片段:

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 做到这一点吗?

最佳答案

这会做你需要的:

  • 请注意,我为复选框指定了类 enable
  • 我还在实际的 html 输入中添加了 disabled 属性,您需要将其添加到您的 php 代码中
  • 我还为每个输入赋予了唯一的名称如果您允许多个字段并将提交表单,则它们都需要唯一的名称

$('.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
});
<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>

关于javascript - 将复选框与另一个输入相关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com