最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Delete Table row using javascript - Stack Overflow

programmeradmin1浏览0评论

I have an HTML table with insert and delete row functionality and its working perfectly. But delete functionality works with checkbox + delete button.

When i want to delete a row, first i checked the checkbox and then press delete button. I want to make it directly with delete button. Below is my code,

function deleteRow(tableID)
{
try
     {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++)
            {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if (null != chkbox && true == chkbox.checked)
                {
                if (rowCount <= 1)
                    {
                    alert("Cannot delete all the rows.");
                    break;
                    }
                table.deleteRow(i);
                rowCount--;
                i--;
                }
            }
        } catch(e)
            {
            alert(e);
    }
   getValues();
}

<a onclick="deleteRow('dataTable')">Delete Row</a>

<table id="dataTable">
  <tr>
    <td><input type="checkbox" name="chk"/></td>
    <td><input type="text" name="Name"></td>
  </tr>
</table>

Note : Atleast 1 row should be there (Cannot delete all the rows)

I have an HTML table with insert and delete row functionality and its working perfectly. But delete functionality works with checkbox + delete button.

When i want to delete a row, first i checked the checkbox and then press delete button. I want to make it directly with delete button. Below is my code,

function deleteRow(tableID)
{
try
     {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++)
            {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if (null != chkbox && true == chkbox.checked)
                {
                if (rowCount <= 1)
                    {
                    alert("Cannot delete all the rows.");
                    break;
                    }
                table.deleteRow(i);
                rowCount--;
                i--;
                }
            }
        } catch(e)
            {
            alert(e);
    }
   getValues();
}

<a onclick="deleteRow('dataTable')">Delete Row</a>

<table id="dataTable">
  <tr>
    <td><input type="checkbox" name="chk"/></td>
    <td><input type="text" name="Name"></td>
  </tr>
</table>

Note : Atleast 1 row should be there (Cannot delete all the rows)

Share edited Dec 1, 2013 at 12:37 Arif asked Dec 1, 2013 at 12:29 ArifArif 1,2116 gold badges31 silver badges60 bronze badges 5
  • where exactly is the delete button? do you have one below the table and you want to delete the focused row? or one delete button besides each row? – melc Commented Dec 1, 2013 at 12:35
  • @melc ohhh sorry i forget to add delete button, I updated my question, now check it – Arif Commented Dec 1, 2013 at 12:38
  • 3 If you use only the delete button how do you plan to identify which row(s) should be deleted? – David Thomas Commented Dec 1, 2013 at 12:40
  • @DavidThomas yes I used delete button directly with each row but it delete all rows. I think if we use 1 specific ID with that button but i don't have any idea how to do it – Arif Commented Dec 1, 2013 at 12:43
  • 1 Why are you plicating this? Stick with the checkbox, it's a user-interface people are familiar with, and far less plex than trying to guess which row should be acted on. And using an id would identify a particular row, yes. But what should happen on the second click, or the third? – David Thomas Commented Dec 1, 2013 at 12:51
Add a ment  | 

2 Answers 2

Reset to default 4

If you want to use one button, a usable solution is to select/unselect the rows to be deleted onclick. This way multi select and delete is also supported. For example,

http://jsfiddle/Nt4wZ/

js

function selectRow(row) {
    if (row.className.indexOf("selected") != -1) {
        row.className = row.className.replace("selected", "");
    } else {
        row.className += " selected";
    }
}

function deleteRow(tableID) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for (var i = 0; i < rowCount; i++) {
            var row = table.rows[i];
            /*var chkbox = row.cells[0].childNodes[0];*/
            /*if (null != chkbox && true == chkbox.checked)*/

            if (row.getElementsByTagName("input")[0].className.indexOf("selected")!=-1) {
                if (rowCount <= 1) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    } catch (e) {
        alert(e);
    }
    //getValues();
}

html

<a onclick="deleteRow('dataTable')">Delete Row</a>

<table id="dataTable">
    <tr>
        <!-- <td><input type="checkbox" name="chk"/></td> -->
        <td>
            <input type="text" name="Name" onclick="selectRow(this)" />
        </td>
    </tr>
    <tr>
        <!-- <td><input type="checkbox" name="chk"/></td> -->
        <td>
            <input type="text" name="Name" onclick="selectRow(this)" />
        </td>
    </tr>
</table>

css

input.selected {
    border-color:lightgreen;
}

EDIT - response to ments

If you want to have a delete button for each row and use that instead, you can do something like the following,

http://jsfiddle/GRgMb/

html

<table id="dataTable">
    <tr>
        <!-- <td><input type="checkbox" name="chk"/></td> -->
        <td>
            <input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
        </td>
    </tr>
    <tr>
        <!-- <td><input type="checkbox" name="chk"/></td> -->
        <td>
            <input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
        </td>
    </tr>
</table>

js

function deleteRow(tableID,currentRow) {
    try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for (var i = 0; i < rowCount; i++) {
            var row = table.rows[i];
            /*var chkbox = row.cells[0].childNodes[0];*/
            /*if (null != chkbox && true == chkbox.checked)*/

            if (row==currentRow.parentNode.parentNode) {
                if (rowCount <= 1) {
                    alert("Cannot delete all the rows.");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
    } catch (e) {
        alert(e);
    }
    //getValues();
}

This code is an example:

    $(document).on('click', 'img.imgdel', function deleteRow() {
      $(this).closest('tr').remove();
      return false;
   });

https://codepen.io/dionejpmc/pen/vYxLdyX

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>