2017-01-22 222 views
0

我有PHP的循環,其返回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

你要找的是.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(); 
}); 
+0

讓我來試試這個 –

+0

其顯示'未捕獲的語法錯誤:參數list'後失蹤)在控制檯日誌 –

+0

謝謝我修復它。它現在工作。 –

相關問題