2014-12-24 54 views
0

從數據庫中的另一個的選擇框的改變事件選擇框的值我有一個視圖文件作爲更改對笨

<select name="tournaments" id ="tournaments" class="form-control"> 
<?php foreach ($tournaments as $tournament): ?> 
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option> 
<?php endforeach ?> 
</select> 

腳本

<script type="text/javascript"> 
    $(document).ready(function(){ 
     var initial_target_html = '<option value="">Please select a Tournament...</option>'; //Initial prompt for target select 
     $('#matches').html(initial_target_html); 
     $("#tournaments").change(function(e){ 
      e.preventDefault(); 
      var data = ($("#tournaments").val()); 
      $('#matches').html('<option value="">Loading...</option>'); 
      $.ajax({ 
       type:"POST", 
       dataType: 'json', 
       url:"<?php echo base_url('admin/dashboard/update_match_box') ?>", 
       data: {tournament:data}, 
       success: function(data) { 

       } 
      }); 
     }); 
    }); 
</script> 

控制器功能是

public function update_match_box() 
{ 
    $sql = "Some query" 
    $query = $this->db->query($sql); 
    $json= $query->result(); 
    $this->output->set_content_type('application/json') 
     ->set_output(json_encode($json)); 
} 

控制器文件將返回多個行,我需要在成功事件中捕獲ajax並相應地更新第二個選擇框,我想怎麼做?

回答

0

你應該看看form_helper文件中,有建設形式投入了大量的有用的功能,你所要做的就是加載這個幫手: 在的application/config/autoload.php去「幫手「並添加輔助名稱如下:

$autoload['helper'] = array('form'); 

下一步,進入到您的視圖文件,更改此:

<select name="tournaments" id ="tournaments" class="form-control"> 
<?php foreach ($tournaments as $tournament): ?> 
<option value="<?php echo $tournament->TournamentID ?>"><?php echo $tournament->TournamentName ?></option> 
<?php endforeach ?> 
</select> 

這樣:

<?php 
// $tournaments must me an array, use ->result_array() instead of ->result_object() 
$tournaments = array_column($tournaments, 'TournamentName', 'TournamentID'); 
echo form_dropdown('tournaments', $tournaments, '', 'id="tournaments" class="form-control") 
?> 

爲您的成功回調函數,你可以使用$。每或只爲循環提取每個元素,併爲選擇輸入選項:

$.ajax({ 
    type:"POST", 
    dataType: 'json', 
    url:"<?php echo base_url('admin/dashboard/update_match_box') ?>", 
    data: {tournament:data}, 
    success: function(data) { 
    $('select#secondSelect').html(''); 
    $.each(data, function(item) { 
     $("<option />").val(item.id) 
         .text(item.name) 
         .appendTo($('select#secondSelect')); 
    }); 
    } 
});