【问题标题】:Javascript - Append row -dependent drop down listJavascript - 附加行相关的下拉列表
【发布时间】:2017-11-08 08:06:52
【问题描述】:

我需要帮助来解决我的依赖下拉列表克隆问题。我有这三个字段,1.country_name,2.store_model,3.location_list,在选择 country_name 时将填充 store_model,在选择 store_model 时将填充位置列表。这工作正常,但是当我尝试克隆并附加一行时,附加的下拉列表无法正常工作。在附加的下拉列表中,值根据原始下拉选择显示。

这是我的 PHP 页面

        <!-- BEGIN FORM-->
    <form action="functions.php"  method="post" enctype="multipart/form-data"
    class="form-horizontal form_emp" id="form_sample_3" novalidate="novalidate">
    <div class="form-body">
    <input type="hidden"  class="form-control" value="<?php echo $id;?>" name="id">
    <input type="hidden"  class="form-control" value="<?php echo $sp_id;?>" name="sp_id">
    <input type="hidden"  class="form-control tot_in" value="0" name="total_in">
    <div class="row">
    <div class="col-md-12">
    <div class="table-scrollable">
    <table class="table table-bordered edit-table">
    <thead>
    <tr>                                                                    
    <th width="10%"> # </th>
    <th width="20%"> Country </th>
    <th width="20%"> Store Model</th>
    <th width="20%"> Loaction</th>
    <th width="30%"> Update Comments </th>                                  
    </tr>
    </thead>

    <tbody id="items-row">
    <?php
    if(empty($userdata)):
    ?>                                                                  
    <tr class="item-row">                                                   
    <td>

    <a title="Remove row" href="javascript:;" class="dodelete delete btn red btn-outline">
    <i class="fa fa-trash-o"></i></a></td>

    <td class="form-group form-md-line-input">
    <select multiple="multiple" class="form-control country_name" name="country_name[]">
    <?php $q=mysql_query("SELECT `id`,`country_name` FROM `db_country` WHERE  id in (select distinct country_id from db_locations where location_id in (select location_id from db_sp where sp_id=$sp_id)) ");
    while($res=mysql_fetch_array($q)){
    echo "<option ".(in_array($res['id'],$country_name)?"selected":"")." value='".$res['id']."'>".$res['country_name']."</option>"; 
    }?>
    </select>
    </td>

    <td class="form-group form-md-line-input">
    <select multiple="multiple" class="form-control store_model" name="store_model[]">
    <?php
    $q=mysql_query("SELECT `id`,`store_model` FROM `db_store_model` WHERE  id in (select distinct store_model_id from db_locations where location_id in (select location_id from db_sp where sp_id=$sp_id)) ");
    while($res=mysql_fetch_array($q)){
    echo "<option ".(in_array($res['id'],$store_model)?"selected":"")." value='".$res['id']."'>".$res['store_model']."</option>";   
    }?>
    </select>
    </td>

    <td class="form-group form-md-line-input">
    <select multiple="multiple" class="form-control location_list" name="location_list[]">
    <?php
    if(!empty($id)){
    $q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE  location_id in (select location_id from db_sp where sp_id=$sp_id)");
    while($res=mysql_fetch_array($q)){
    echo "<option ".(in_array($res['location_id'],$location_list)?"selected":"")." value='".$res['location_id']."'>".$res['location_name']."</option>"; 
    }}?>
    </select>
    <div class="form-control-focus loading"> </div>
    </td>

    <td align="centre" class="form-group form-md-line-input"> 
    <input type="text" class="form-control" name="comments[]"></td>
    </tr>

    <?php 
    else:
    $count=count($sp_detail);
    for($i=0; $i<$count;$i++){
    ?>
    <tr class="item-row">

    <a title="Remove row" href="javascript:;" class="dodelete delete btn red btn-outline">
    <i class="fa fa-trash-o"></i></a></td>
    <td class="form-group form-md-line-input"> 
    <select multiple="multiple"  class="form-control country_name" name="country_name[]">
    <option value="">Select Any</option>
    <?php foreach($country_name as $key=>$cname){ ?>
    <option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['country_name']==$key?"selected":"");?>><?php echo $cname ;?></option>
    <?php }?>
    </select>

    </td>
    <td class="form-group form-md-line-input"> 
    <select multiple="multiple"  class="form-control store_model" name="store_model[]">
    <option value="">Select Any</option>
    <?php foreach($store_model as $key=>$smodel){ ?>
    <option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['store_model']==$key?"selected":"");?>><?php echo $smodel ;?></option>
    <?php }?>
    <div class="form-control-focus loading"> </div>
    </td>

    <td class="form-group form-md-line-input"> 
    <select multiple="multiple"  class="form-control location_list" name="location_list[]">
    <option value="">Select Any</option>
    <?php foreach($location_list as $key=>$loclist){ ?>
    <option value="<?php echo $key ;?>" <?php echo ($sp_detail[$i]['location_list']==$key?"selected":"");?>><?php echo $loclist ;?></option>
    <?php }?>
    </select>
    <div class="form-control-focus loading"> </div>
    </td>
    </tr>



    <?php   
    }
    endif;
    ?>
    </tbody>

    </table>

    </div>
    </div>
    </div>
    <div class="row">

    <div class="col-md-2">
    <a title="Add a row" href="javascript:;" class="addrow btn blue btn-outline">Add a row</a>


    </div>

    <div class="col-md-8 invoice-block text-right">
    <div class="form-group form-md-line-input">
    <label class="col-md-3 control-label" for="form_control_1">Update Type
    <span class="required">*</span>
    </label>
    <div class="col-md-6">
    <select class="form-control" name="event_status">
    <option value="1">Update</option>
    </select>
    <div class="form-control-focus"> </div>
    </div>
    </div>
    </div>
    </div>
    </div>
    <div class="form-actions">
    <div class="row">
    <div class="col-md-offset-3 col-md-6">
    <button type="submit" name="action" value="update_event" class="btn green">Submit</button>
    <button type="reset" class="btn default reset">Reset</button>
    </div>
    </div>
    </div>
    </form>
    <!-- END FORM-->

这是我的functions.php

        if(isset($_POST['action'])&& $_POST['action']=='selectUpdate'){
    $post=$_POST;

$country_id=json_encode($post['country_name']);
$country_ids=join(',',$post['country_name']);
$sp_id=$post['sp_id'];

$store_model_id=json_encode($post['store_model']);
$store_model_ids=join(',',$post['store_model']);

    $q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE country_id in ($country_ids) and store_model_id in ($store_model_ids) and location_id in (select location_id from db_sp where sp_id=$sp_id)order by country_id,store_model_id");
$qno=mysql_num_rows($q);

if($qno>0){
    while($res=mysql_fetch_array($q)){
        echo "<option value='".$res['location_id']."'>".$res['location_name']."</option>";
    }
}
else{
    echo "<option value=''>No Data</option>";
}
    }

这是我的 JavaScript

<script>

$(document).ready(function(){

$(document).on('click','.dodelete',function(){
    if($('.edit-table #items-row').find('tr').length > 1) { $(this).parents('tr').remove(); }
    else{alert('All rows cant be deleted');}

});

var setSelectsEvents = function(rowElement) {
    $(rowElement).on('change', '.country_name,.store_model', function(){
        var store_model=$(rowElement).find('.store_model')[0].value;
        var country_name=$(rowElement).find('.country_name')[0].value;
        var sp_id=<?php echo $sp_id ?>;
        //var store_model=$(this).val();
        $('.loading').html('<img src="layouts/layout/img/loading.gif"/>');
        $.ajax({
         type: 'post',
         url: 'functions.php',
         data: {
           sp_id:<?php echo $sp_id ?>,store_model:store_model,country_name:country_name, action:"selectUpdate",
         },

         success: function (res) {
            $('.loading').html("");
            $($(rowElement).find('.location_list')[0]).html(res); 
            $('#my_multi_select1').multiSelect();
         }
       });
    });
};
setSelectsEvents('.item-row');

$('.addrow').click(function(){
    var elem = $('#items-row').find('tr:first').clone();
    var appendedRow = $('#items-row').append(elem).children(':last-child');
    setSelectsEvents(appendedRow);
});

$(document).on('click','.reset',function(){
    emptyTable();
});

});

$(函数(){ $('.datepicker').datepicker({ 格式:'yyyy-mm-dd', 开始日期:'日期今天', //开始日期:'+15d', 自动关闭:真 }); });

我不擅长 JavaScript,在某个地方我犯了错误。请帮忙。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    我认为它有一些事件处理程序,例如 $('select.coutry_name').on('change', ... 但是这些事件处理程序没有设置克隆行选择。 所以它会正常工作选择事件处理程序部分和 $('.addrow').click 更改为如下所示。

    // **UPDATED JavaScript**
    
    <script>
    $(document).ready(function(){      
    
    
        $(document).on('click','.dodelete',function(){
            if($('.edit-table #items-row').find('tr').length > 1) { $(this).parents('tr').remove(); }
            else{alert('All rows cant be deleted');}
    
        });
    
        var setSelectsEvents = function(rowElement) {
            $(rowElement).on('change', '.country_name,.store_model', function(){
                var store_model=$($(rowElement).find('.store_model')[0]).val();
                var country_name=$($(rowElement).find('.country_name')[0]).val();
                var sp_id=<?php echo $sp_id ?>;
                //var store_model=$(this).val();
                $('.loading').html('<img src="layouts/layout/img/loading.gif"/>');
                var data = {
                  sp_id:1,store_model:store_model,country_name:country_name, action:"selectUpdate",
                };
                $('.loading').html('<img src="/images/loading.gif"/>');
                $.ajax({
                  type: 'post',
                  url: 'functions.php',
                  data: JSON.stringify(data),
                  contentType: 'application/JSON',
                  dataType : 'JSON',
    
                  success: function (res) {
                    $('.loading').html("");
                    $($(rowElement).find('.location_list')[0]).html(res); 
                    $('#my_multi_select1').multiSelect();
                  }
                });
            });
        };
        setSelectsEvents('.item-row');
    
        $('.addrow').click(function(){
            var elem = $('#items-row').find('tr:first').clone();
            var appendedRow = $('#items-row').append(elem).children(':last-child');
            setSelectsEvents(appendedRow);
        });
    
        $(document).on('click','.reset',function(){
            emptyTable();
        });
    
    
    });
    
    $(function(){
        $('.datepicker').datepicker({
            format: 'yyyy-mm-dd',
            startDate: 'dateToday',
            //startDate: '+15d',
            autoclose: true
        });
    });
    
    
    
    </script>
    

    【讨论】:

    • 谢谢,我已更新问题中的完整 Javascript,我已根据您的建议对其进行了更改,但我无法使其按预期工作。请指教。
    • 我看到了你的更新。它需要再修改一点。我已经复制并修改了您更新的脚本,并将我的脚本更新为该脚本。那怎么样?
    • 谢谢,我已经更新了代码,现在选择国家和商店模式后位置列表没有填充。请帮忙
    • 查看浏览器开发者工具,有没有报错?
    • 在第一行选择,国名和店铺模式有效,选择国名和店铺模式后,位置列表不显示。
    【解决方案2】:

    它是以 JSON 格式发布的数据,必须在 PHP 上解码 JSON 数据。

    if(isset($_POST['action'])&& $_POST['action']=='selectUpdate'){
        $post=json_decode($_POST, true);
    
        //$country_id=json_encode($post['country_name']);  //not used
        $country_ids=is_array($post['country_name']) ? join(',',$post['country_name']) : $post['country_name'];
        $sp_id=$post['sp_id'];
    
        //$store_model_id=json_encode($post['store_model']);  //not used
        $store_model_ids=is_array($post['store_model']) ? join(',',$post['store_model']) : $post['store_model'];
    
        $q=mysql_query("SELECT `location_id`,`location_name` FROM `db_locations` WHERE country_id in ($country_ids) and store_model_id in ($store_model_ids) and location_id in (select location_id from db_sp where sp_id=$sp_id)order by country_id,store_model_id");
        $qno=mysql_num_rows($q);
    
        if($qno>0){
            while($res=mysql_fetch_array($q)){
                echo "<option value='".$res['location_id']."'>".$res['location_name']."</option>";
            }
        }
        else{
            echo "<option value=''>No Data</option>";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-14
      • 2013-10-19
      • 2013-01-25
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多