html 追加表中的空数据

Empty data in html append table

本文关键字:数据 追加 html      更新时间:2023-09-26

我有以下脚本,当选择下拉值时,它会用数据填充表:

<script>
     $(document).ready(function(){
     $('#commodity_name').change(function (){
         //picks the value of the selected commodity_name from the dropdown
         option = $(this).find('option:selected').val();
         html='';
         htmlhead='';
        // alert(option)
         $.ajax({
             type:"GET",
             //gets data from the url specified based on the selected commodity_name in the dropdown
             url:"<?php echo base_url();?>user_transactions/return_details/"+option,
             dataType:"json",
             success:function(data){
                for(i=0;i<data.length;i++){
                //Loops through the data to give out the data in a table format
                    //alert(data[i].transaction_type)
         html += '<tr>'n'
        <td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="'+data[i].commodity_name+'"/></td>'n'
        <td><input type="text" id="transaction_type' + i + '" name="transaction_type[]" value="'+data[i].transaction_type+'"/></td>'n'
        <td><input type="text" id="total_quantity' + i + '" name="total_quantity[]" value="'+data[i].total_quantity+'"/></td>'n'
        <td><input type="text" id="remarks' + i + '" name="remarks[]" value="'+data[i].remarks+'"/></td>'n'
        <td><input type="text" id="unit_cost' + i + '" name="unit_cost[]" value="'+data[i].unit_cost+'"/></td>'n'
        <td></td><td></td></tr> ';
        }
        htmlhead+=''n'
             <th>Commodity Name</th>'n'
             <th>Transaction Type</th> 'n'
            <th>Available  Quantity</th>         'n'
            <th>Available  Quantity</th> 'n'
            <th>Department</th>'n'
            <th>Requestor Name</th>'n'
            ';
                                //alert(html);
                                //alert(htmlhead);
       $('#thead').append(htmlhead);
        $('#you').append(html);
        //delegated submit handlers for the forms inside the table
$('#issue_1').on('click', function (e) {
    e.preventDefault();
    //read the form data ans submit it to someurl
    $.post('<?php echo base_url()?>transactions/issues', $('#Issues_Form').serialize(), function () {
        //success do something
        alert("Success");
        var url = "<?php echo base_url()?>transactions/view_request";    
        $(location).attr('href',url);
    }).fail(function () {
        //error do something
        alert("Failed please try again later or contact the system Administrator");
    })
})
             },
             error:function(data){
             }
         })
     });
     });

</script>

当我在下拉列表中选择下一个commodity_name时,如何从已附加的html表中清除数据,我只获得从下拉列表中选择的新选择返回的数据。

只需在追加之前清空 html。

...
$('#thead').empty();
$('#you').empty();
$('#thead').append(htmlhead);
$('#you').append(html);
...

尝试使用 Jquery 的 .detach() 方法。这里是链接:http://api.jquery.com/detach/