我有php for循环,它带有输入框的12复选框。
<div class="row">
<div class="col-md-4">
<?php
$getChannel = mysqli_query($conn, "SELECT ch_id, ch_name, ch_for FROM channel WHERE lg_id = '$lg_id' ");
$ch_for = array();
$ch_name = array();
while ( $fetchChannel = mysqli_fetch_array($getChannel) ) {
$ch_id = (int) $fetchChannel['ch_id'];
$ch_for[] = htmlspecialchars($fetchChannel['ch_for']);
$ch_name[] = htmlspecialchars($fetchChannel['ch_name']);
}
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x, $ch_name)) {
$sel = 'checked = "checked" ';
} else {
$sel = '';
}
?>
<div class="checkbox form-inline">
<label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">CH<?php echo $x; ?></label>
<input type="text" name="ch_for[]" value="" placeholder="Channel details" class="form-control ch_for">
</div>
<?php
}
?>
</div>
如果$ch_name
与for循环'ch'.$x
匹配,那么我选中了复选框。
现在我想使用jQuery显示相应的输入框,其中已经选中了复选框。
jQuery代码:
$('.ch_for').hide();
if ( $('.checkbox input:checkbox:checked').length > 0 ) {
$(this).closest('.checkbox').find('.ch_for').show();
}
$('.checkbox input:checkbox').on('click', function(){
$(this).closest('.checkbox').find('.ch_for').toggle('slow');
})
答案 0 :(得分:0)
您正在寻找的是.each功能:
// no-conflict safe document ready (shorthand version)
jQuery(function($) {
// hide all of the inputs initially
$('.ch_for').hide();
// your original function to show / hide on click
$('.checkbox input:checkbox').on('click', function() {
$(this).closest('.checkbox').find('.ch_for').toggle('slow');
});
// put this in a function for reusability
function showInputs() {
// use .each to loop over every checked input
$('.checkbox input:checkbox:checked').each(function() {
// inside .each, $(this) refers to the checkbox element
$(this).closest('.checkbox').find('.ch_for').show();
});
}
// call the function on initial load
showInputs();
});