1

I have two dropdowns: #GameVenueId and #GameHometeamId. Each Venue has a default Hometeam, so when #GameVenueId is changed, I'd like to update #GameHometeamId with the default Hometeam. (I also want the user to be able to select a different hometeam in the case of rare exceptions, so that's why I am using dropdowns.) When a user changes the selection in #GameVenueId, I have a JSON object that maps the ID of the Venue to the ID of its default Hometeam. I'd like to use CakePHP's JS helper to accomplish this, but I'm having no luck.

View:

$this->start('script');
echo $this->Html->script('jquery-1.10.2.min');
$this->Js->get('#GameVenueId');
$this->Js->event('change', 
    // insert code here
);
echo $this->Js->writeBuffer();
$this->end();

Controller:

$homefields = $this->Team->find('list', array(
    'fields' => array('Team.id', 'Team.venue_id'),
));
$this->set(compact('homefields'));

$homefields, once it has been passed through json_encode(), looks like this:

{"1":"1","2":"2","3":"5","4":"6","5":"7","6":"8","7":"10","8":"11","9":"12","10":"13","11":"14","12":"16","13":"15","14":"17"}

Now, I have some code written out, totally untested because I can't get CakePHP to execute it, which is why I am trying to get this accomplished through the JS helper instead:

$('#GameVenueId').change(function(){
    var n = $(this).val();
    var homefield = jQuery.parseJSON( '".json_encode($homefields)."' );
    $('#GameHometeamId option').filter(function() {
        return ($(this).val() == homefield.n);
    }).prop('selected', true);
});

I suppose there are a few solutions: either do this through JS helper or find a way to format the code so that it actually gets executed. Any help would be awesome.

4

1 回答 1

1

最好直接使用jQuery。CakePHP 的 JS 助手不会很灵活。我认为下面的代码会起作用。

var homefield = <?php echo json_encode($homefields);?>
$('#GameVenueId').change(function(){
    var n = $(this).val();
    $('#GameHometeamId').val(homefield[n]);
});
于 2013-10-01T11:30:28.317 回答