在php和jquery中动态创建的表行中选择与加载的数据相对应的选项另一个选择选项


Select an option corresponding data loaded another select option in dynamically created table rows in php and jquery

这是我在html和jquery中创建动态行的代码

<div class='col-xs-12 col-sm-12 col-md-12 col-lg-12'>
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th width="2%"><input id="check_all" class="formcontrol" type="checkbox"/></th>
                        <th width="14%">Item No</th>
                        <th width="14%">Item Name</th>
                        <th width="14%">Category</th>
                        <th width="14%">Price</th>
                        <th width="14%">Quantity</th>
                        <th width="14%">Type</th>
                        <th width="14%">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><input class="case" type="checkbox"/></td>
                        <td><input type="text" data-type="product_code" name="productcode[]" id="itemNo_1" class="form-control autocomplete_txt" autocomplete="off" required></td>
                        <td><input type="text" data-type="product_name" name="productname[]" id="itemName_1" class="form-control autocomplete_txt" autocomplete="off" required></td>
                        <td><select name="category[]" class="form-control txt" id="category_1"></select></td>
                        <td><input type="number" name="price[]" id="price_1" class="form-control changesNo" autocomplete="off" onKeyPress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" required></td>
                        <td><input type="number" name="quantity[]" id="quantity_1" class="form-control changesNo" autocomplete="off" onKeyPress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" required></td>

                        <td><select class="form-control" name="prdtype[]">
                        <option value="Prepaid">Prepaid</option>
                        <option value="Postpaid">Postpaid</option>
                       </select></td>

                        <td><input type="number" name="total[]" id="total_1" class="form-control totalLinePrice" autocomplete="off" onKeyPress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" readonly></td>
                    </tr>
                </tbody>
            </table>
                        </div>
<div class='col-xs-12 col-sm-3 col-md-3 col-lg-3'>
            <button class="btn btn-default delete" type="button"><b>- Delete</b></button>
            <button class="btn btn-default addmore" type="button"><b>+ Add New</b></button>
        </div>

我单击添加新按钮,使用此代码创建另一行

var i=$('table tr').length;
var clicks = 1; $(".addmore").click(function(){ clicks++;});
$(".addmore").on('click',function(){
    html = '<tr>';
    html += '<td><input class="case" type="checkbox"/></td>';
    html += '<td><input type="text" data-type="product_code" name="productcode[]" id="itemNo_'+i+'" class="form-control autocomplete_txt" autocomplete="off" required></td>';
    html += '<td><input type="text" data-type="product_name" name="productname[]" id="itemName_'+i+'" class="form-control autocomplete_txt" autocomplete="off" required></td>';
    html += '<td><select name="category[]" class="form-control txt" id="category_'+clicks+'"></select></td>';
    html += '<td><input type="text" name="price[]" id="price_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" required></td>';
    html += '<td><input type="text" name="quantity[]" id="quantity_'+i+'" class="form-control changesNo" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" required></td>';
    html += '<td><select class="form-control" name="prdtype[]"><option value="Prepaid">Prepaid</option><option value="Postpaid">Postpaid</option></select></td>';
    html += '<td><input type="text" name="total[]" id="total_'+i+'" class="form-control totalLinePrice" autocomplete="off" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" readonly></td>';
    html += '</tr>';
    $('table').append(html);
    i++;
});
//to check all checkboxes
$(document).on('change','#check_all',function(){
    $('input[class=case]:checkbox').prop("checked", $(this).is(':checked'));
});
//deletes the selected table rows
$(".delete").on('click', function() {
    $('.case:checkbox:checked').parents("tr").remove();
    $('#check_all').prop("checked", false); 
    calculateTotal();
});

自动完成字段是Itom No和Item Name,这里是自动完成的代码

 //autocomplete script
$(document).on('focus','.autocomplete_txt',function(){
    type = $(this).data('type');
    if(type =='product_code' )autoTypeNo=0;
    if(type =='product_name' )autoTypeNo=1;     
    $(this).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url : 'ajax.php',
                dataType: "json",
                method: 'post',
                data: {
                   name_startsWith: request.term,
                   type: type
                },
                 success: function( data ) {
                     response( $.map( data, function( item ) {
                        var code = item.split("|");
                        return {
                            label: code[autoTypeNo],
                            value: code[autoTypeNo],
                            data : item
                        }
                    }));
                }
            });
        },
        autoFocus: true,            
        minLength: 0,
        select: function( event, ui ) {
            var names = ui.item.data.split("|");                        
            id_arr = $(this).attr('id');
            id = id_arr.split("_");
            $('#itemNo_'+id[1]).val(names[0]);
            $('#itemName_'+id[1]).val(names[1]);
            $('#quantity_'+id[1]).val(1);
            $('#price_'+id[1]).val(0);
            $('#total_'+id[1]).val( 1*0 );
            getcategory(names[2])
            calculateTotal();
        }               
    });
});

在ajax.php页面

<?php
require_once '../model/config.php';
if(!empty($_POST['type'])){
    $type = $_POST['type'];
    $name = $_POST['name_startsWith'];
    $query = "SELECT id,product_code,product_name FROM products where UPPER($type) LIKE '".strtoupper($name)."%'";
    $result = mysqli_query($con, $query);
    $data = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $name = $row['product_code'].'|'.$row['product_name'].'|'.$row['id'];
        array_push($data, $name);
    }   
    echo json_encode($data);exit;
}



if(isset($_POST['cat']) && $_POST['cat'] == 'category' ){
    $id = $_POST['id'];
    $query = "SELECT * FROM product_category WHERE product_id =$id";
    $result = mysqli_query($con, $query);
    $category = '';
    while($data = mysqli_fetch_assoc($result))
    {
    if(!empty( $data )){
        echo "<option>".$data['category']."</option>";
    }
    }
    mysqli_close($con);
    exit;
}
?>

当我在"类别"字段中选择"项目编号"或"项目名称"及其相应的"类别"显示时,我使用此代码选择类别

function getcategory(id){
         $.ajax({
             url: "ajax.php",
             method: 'post', 
             data:{id:id, cat:'category'},
             success: function(result){
                $("#category_'+clicks+'").html(result);
            }
        });
    }

但我添加了第二行或第三行类别,没有显示在当前条件下的类别字段中

请访问此链接进行在线演示http://sealinesagro.com/form/

在这种形式中,itom no 001有3个子类别
1:HLR1
2:HLR2
3:HLR3
和Itom No 003有3个子类别
1:HLR新1
2:HLR新2
3:HLR新3

var clicks = 1;
$(".addmore").click(function(){ clicks++;});
$(".addmore").on('click',function(){

您基本上在$( '.addmore' )上重新绑定了click事件。第二行代码将被忽略,这将影响类别的select的id。因此,当您尝试在getcategory(id)函数中分配提取的数据时,数据不会分配给select。更新上述代码:

var clicks = 1;
$(".addmore").on('click',function(){
    click++;

希望这能解决你的问题。祝你好运,玩得开心!