2012-10-01 95 views
2

我有一个html表,并在每一行上,我想添加一个删除按钮。 当用户点击它时,我想做两件事:如何从表中删除一行

1)从表中删除该行。 2)从被删除的行中提取数据 - 一个特定的单元格,然后使用该值将ajax调用到将从数据库中删除记录的函数。该函数返回一个新的项目列表,然后我将使用它重新显示相同的表格。

我发现从别人以下职位上计算器: How to remove current row from table in jQuery?

所以我想这点的地址数之一。但我不知道如何修改帖子的选定答案中的代码,以便获取行中的id值,然后进行ajax调用。

 <table class="table table-bordered table-striped" id="databaserecords"> 
     <thead> 
      <tr> 
       <th>Id</th> 
       <th>Name</th> 
       <th>Status</th> 
       <th>Voice</th> 
       <th>Jumbo</th> 
       <th>Mode</th> 
       <th>&nbsp;</th> 
      </tr> 
     </thead> 
     <tbody> 

      <?php foreach ($dblist as $record): ?> 
       <tr>   
       <td class ='recordId'><?php echo $record['Id'] ?></td> 
       <td class ='recordName'><?php echo $record['Name'] ?></td> 
       <td><?php echo $record['Status'] ?></td> 
       <td><?php echo $record['Voice'] ?></td> 
       <td><?php echo $record['Jumbo'] ?></td> 
       <td class='recordmode'><?php echo $record['Mode'] ?></td> 
       <td><button id="deleteRecord">Delete Record</button></td> 
      </tr> 
      <?php endforeach ?> 


<script> 

    $('#deleteRecord').live('click', function() { 

       //get a count of all records. only allowed to delete if you have more than one record. 
       var recCount = $('#databaserecords tbody tr').length; 

       if (recCount > 1) 
       { 
        $thevalueIwanttoSave = $(this).closest('recordId').val(); 
           alert($thevalueIwanttoSave); 
          } 

    }); 

</script> 

现在,警报总是说我的变量是未定义的。 你能指出我正确的方向吗?我知道如何编写ajax调用...我想我只需要帮助从表格中获取值。

谢谢。

回答

2

您选择是不正确的。

$thevalueIwanttoSave = $(this).parent().siblings('.recordId').text(); 

closest选择元件(的recordId不是父母/祖父母或您的按钮元素的..)最亲密的父母和你也错过了.类选择。 val用于获取/设置表单元素的值,对于td元素您应该使用texthtml方法。另请注意,ID必须是唯一的(您可以使用类代替)并且live方法已过时,您可以使用on方法。

$('#databaserecords').on('click', '.deleteRecord', function() { 

    var recCount = $('#databaserecords tbody tr').length; 

    if (recCount > 1) { 
     var text = $(this).parent().siblings('.recordId').text(); 
     alert(text); 
     // $(this).closest('tr').remove() 
    } 

});​ 
-1

将ID添加到删除按钮的属性中,然后通过jQuery获取它。

在你的PHP循环:

<button class="deleteRecord" recordID="<?php echo $record['Id'] ?>">Delete Record</button>
在JQuery中

$(".deleteRecord").click(function() { 
    var id = $(this).attr("recordID"); 
    ... 
});
-1

应该.recordId,不recordId

$thevalueIwanttoSave = $(this).closest('.recordId').val(); 
    alert($thevalueIwanttoSave); 
0
$thevalueIwanttoSave = $(this).parent('tr').find('.recordId').text(); 
-1

您需要使用.选择具有一流的recordId的元素。还可以使用text()来获得值:

$thevalueIwanttoSave = $(this).siblings('.recordId').text(); 
alert($thevalueIwanttoSave);