views:

61

answers:

2

I am trying to use AJAX to populate some select boxes that were autogenerated using CakePHP's formHelper. How do I add the onChange event listener to the select box?

+2  A: 

I solved it by dynamically adding the event listener using the addEventListener() function inside a window.onload() function.

chustar
+1 For figuring it out yourself, following up with what you did and for choosing the "right" way. :-) This is actually a much better solution than the one you requested. Always strive toward unobtrusive javascript.
Rob Wilkerson
@Rob: Agreed. +1 on both.
Michael
+1  A: 
 <?php $html->script('jquery-1.4.2.min',false); ?>
<script type="text/javascript">
    $(document).ready(function(){
        $('#ProductBrandId').change(function(){
            getfamily()
        });
    })

    function getfamily(){
        $.ajax({
                type : "GET",
                url  : "getfamily?id="+$('#ProductBrandId').val()&rid='+Math.random()/9.9,
                success : function(opt){
                    $('#familybox').html(opt)
                }
            })
    }
</script>

admin_getfamily.ctp

<?php
    $options = array(
                 'type' => 'select',
                 'options' => $family,
                 'label' => '',
                 'div' => '',
                 'style' => 'width:235px',
                 'error'=> false,

            );

     echo $form->input(
             'Product.family_id',
             $options
    );
?>

in the controller

function admin_getFamily(){
        $this->layout = '';
        //debug($this->params['url']);
        $brand = $this->params['url']['id'];
        $family = array();
        if($brand > 0){
            $family = $this->Product->Brand->Family->find('list',array('fields' => 'Family.name','conditions' =>array('Family.brand_id' => $brand),'order' => 'Family.name'));
        }
        $this->set(compact('family'));
    }
RSK