2017-12-24 12 views
0

私は、入力フィールドからデータを受け取り、それらをサーバに送信して新しいデータベースレコードを作成する2つのajax呼び出しを持っています。保存が成功した場合は、新しいhtmlテーブル行をhtmlテーブルに追加します。Jquery/Ajax - ajaxコールの後にappendetで動作する

seccond ajax呼び出しは、特定のコストポイントに属するIDをサーバーに送信し、このレコードをデータベースから削除します。

両方の呼び出しがfindeで動作します。しかし、私は、htmlレコードを作成し、再度(ページを更新することなく)それを削除したい場合、それは動作しません。ここで

は私のコードです:テーブルザッツ

function addNewRow(id, name, cost) { 
     $('#costTable tr:last').after('<tr data-id="'+id+'"><td><i class="material-icons">delete forever</i></td><td>' + name + '</td><td>' + cost + '</td></tr>>'); 
    } 

$(document).on('click', '#saveCost', function() { 
      var name = $("input[name='cost-name']").val(); 
      var cost = $("input[name='cost-price']").val(); 
      $.ajax({ 
       type: "post", 
       url: "{{ route('saveCost') }}", 
       data: {'name': name, 'cost': cost}, 
       success: function (data) { 
        swal({ 
         position: 'top-right', 
         type: 'success', 
         title: 'Kostenpunkt wurde gespeichert', 
         showConfirmButton: false, 
         timer: 1000 
        }); 
        $("input[name='cost-name']").val(""); 
        $("input[name='cost-price']").val(""); 
        addNewRow(data, name, cost); 
       }, 
       error: function (data) { 

       } 
      }); //end of ajax 
     }); 
     $(document).on('click', '.deleteCost', function() { 
      var $this = $(this); 
      var costID = $this.closest('tr').data('id'); 
      $.ajax({ 
       type: "post", 
       url: "{{ route('deleteCost') }}", 
       data: {'costID': costID}, 
       success: function (data) { 
        swal({ 
         position: 'top-right', 
         type: 'success', 
         title: 'Kostenpunkt wurde gelöscht', 
         showConfirmButton: false, 
         timer: 1000 
        }); 
        $this.closest('tr').remove(); 
       }, 
       error: function (data) { 

       } 
      }); //end of ajax 
     }); 

<table class="table" id="costTable"> 
     <thead class="text-primary"> 
       <th>Action</th> 
       <th>Kostenpunkt</th> 
       <th>Kosten</th> 
     </thead> 
     <tbody> 
       @foreach($costs as $cost) 
        <tr data-id="{{ $cost->id }}"> 
          <td><i class="material-icons deleteCost">delete forever</i></td> 
          <td>{{ $cost->name }}</td> 
          <td class="text-primary">{{ $cost->cost }}</td> 
        </tr> 
       @endforeach 
     </tbody> 
    </table> 

私は新しい行を作成し、(ページを更新せずに)再びそれを削除したいの後、それはしません作業。私は、 "saveCost" ajax呼び出しにデータを追加し、追加されたデータが実際のHTML DOMに属さないためだと思います。

+0

最初の呼び出しでパスバックIDがありますか?あなたはconsole.log(データ)できますか?新しいレコードのIDが表示されますか? – Victor

答えて

2

addNewRow関数で、この要素にクラス名deleteCostを追加することを忘れてしまった:<i class="material-icons">delete forever</i>。このクラスを追加すると、削除は期待通りに機能します。

+0

あなたは正しいです!ああ男私はとても愚かだった..それを見ていない:Dあなたの助けをありがとう!今完璧に動作します。あなたの答えを正しいものとしてマークします:) – dwdawdawdaw

関連する問題