javascript / jquery更新多个选择框选项

时间:2014-02-04 15:26:23

标签: javascript php jquery cakephp

我在页面上有三个选择框,当有人从第一个框中选择一个选项时,我想通过ajax为第二个框更新选项。当有人更新第二个框时,第三个框通过ajax获得新选项。

我遇到的问题似乎是当用户更新第一个框时,我检查数据库中我需要的选项,然后在php中创建新的选择框并替换原来的选择框。问题是,即使选择框的代码是相同的,并且id与在第二个框中观看更改的原始javascript相同也不再有效。

这里是cakephp / html所有蛋糕正在做的是创建选择框。

    <table>
        <tr>
            <td class="threeCol"><?php echo $this->Form->input('industry', array('type'=>'select', 'options'=>$industries, 'empty'=>'Industry', 'id'=>'industry', 'class'=>'formInputSelect'));?></td>
            <td class="threeCol" id="cateWrap"><?php echo $this->Form->input('category', array('type'=>'select', 'options'=>$categories, 'empty'=>'Category', 'id'=>'category', 'class'=>'formInputSelect'));?></td>
            <td class="threeCol" id="courseWrap"><?php echo $this->Form->input('course', array('type'=>'select', 'options'=>$courses, 'empty'=>'Course', 'id'=>'course', 'class'=>'formInputSelect'));?></td>
        </tr>
    </table>

我使用的javascript:

<script type="text/javascript">
$(document).ready(function() {  
//Update categories dropdown when inustry selected
$("#industry").change(function() {
    if( this.value != "Industry" ) {
        $.post("<?php echo $this->webroot;?>categories/selectoptionsupdate", {id:this.value})
            .done(function (data) {
                $("#cateWrap").html(data);
            });
    } 
});
//Update course dropdown when category selected
$("#category").change(function() {
    if( this.value != "Category" ) {
        $.post("<?php echo $this->webroot;?>courses/selectoptionsupdate", {id:this.value})
            .done(function (data) {
                $("#courseWrap").html(data);
            });
    } 
});

});

最后是创建新盒子的php。

//UPdate the options for the dropdown on post new job page
function selectoptionsupdate() {
    if ($this->request->is('ajax')) {   
        $this->layout = 'ajax';
        $id = $this->request->data['id'];
        $options = $this->Course->find('list', array('conditions'=>array('Course.category_id'=>$id)));
        $result = '';
        $result .= '<select name="data[Job][course]" id="course" class="formInputSelect">';
        $result .= '<option value="">Course</option>';
        foreach($options as $k=>$v) {
            $result .= '<option value="'.$k.'">'.$v.'</option>';
        }
        $result .= '</select>';
        echo 'hey';
    }
}

解决这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

更改行

$("#industry").change(function() {
$("#category").change(function() {

有:

$(document).on("change", "#industry", function() {
$(document).on("change", "#category", function() {

http://api.jquery.com/on/

相关问题