首先我假设你是这样的 php 数组
$cities=array('Adam','Newton');
$stores=array('KFC','Ramen','Sushi','Pizza','Subway');
$city_has_store=array('Adam'=> array("KFC",
"Ramen",
"Subway"
),
'Newton'=> array("Subway",
"Sushi"
)
);
我像这样 foreach 数组
foreach ( $cities as $city ) : ?>
<div style="margin-bottom: 20px;">
<label style="display: block;">
<input type="radio" onclick="changeCheck(this.value);" id="selCity" name="selCity" value="<?php echo $city; ?>"><?php echo $city; ?>
</label>
<?php
foreach ( $stores as $store ) : ?>
<label style="display: block;">
<input type="checkbox" id="<?=$city?>_<?=$store?>" name="selStore" value="<?php echo $store; ?>" disabled><?php echo $store; ?>
</label>
<?php
endforeach;
?>
</div>
<?php
endforeach;
?>
当我对数组进行 foreach 时,我将 onclick="changeCheck(this.value);" 添加到输入单选按钮并将 id 添加到输入复选框中,它结合了 $city 和 $store 值,我首先禁用了所有复选框
在 JavaScript 中
function changeCheck(val) {
//first disable all checkbox
$('input[type="checkbox"]').prop('disabled', true);
// get the array city_has_store
var city_has_store = <?php echo json_encode($city_has_store); ?>;
//get the radio button val when click
var val_radio = val;
//foreach the array city_has_store
for (i = 0; i < city_has_store[val_radio].length ; ++i) {
//and change disabled to false when the input checkbox id like combine $city_$store
$('#'+val_rad+'_'+city_has_store[val_radio][i]).prop('disabled', false);
}
}
完整的代码如下所示
<?php
$cities=array('Adam','Newton');
$stores=array('KFC','Ramen','Sushi','Pizza','Subway');
$city_has_store=array('Adam'=> array("KFC",
"Ramen",
"Subway"
),
'Newton'=> array("Subway",
"Sushi"
)
);
foreach ( $cities as $city ) : ?>
<div style="margin-bottom: 20px;">
<label style="display: block;">
<input type="radio" onclick="changeCheck(this.value);" id="selCity" name="selCity" value="<?php echo $city; ?>"><?php echo $city; ?>
</label>
<?php
foreach ( $stores as $store ) : ?>
<label style="display: block;">
<input type="checkbox" id="<?=$city?>_<?=$store?>" name="selStore" value="<?php echo $store; ?>" disabled><?php echo $store; ?>
</label>
<?php
endforeach;
?>
</div>
<?php
endforeach;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function changeCheck(val) {
//first disable all checkbox
$('input[type="checkbox"]').prop('disabled', true);
// get the array city_has_store
var city_has_store = <?php echo json_encode($city_has_store); ?>;
//get the radio button val when click
var val_radio = val;
//foreach the array city_has_store
for (i = 0; i < city_has_store[val_radio].length ; ++i) {
//and change disabled to false when the input checkbox id like combine $city_$store
$('#'+val_rad+'_'+city_has_store[val_radio][i]).prop('disabled', false);
}
}
</script>