How to delete multiple lines with the click of a button
I want to delete the selected rows by clicking the Delete button. My delete feature works fine, the problem I’m facing is that only the topmost delete button is working, and my UI screen looks like this
I use the checkbox to select table rows. If I select all three records, all three delete buttons should work, and any delete button can delete the selected rows, but in my case, only the first delete button works.
Here is my html and js code.
<td class="td-org">${entry.sORGID}</td>
<td class="td-org">${entry.url}</td>
<td class="td-org">${entry.type}</td>
<td class="td-org"><a href="" onclick="testing("")" />Testing</td>
<td class="td-org"><input type="button" value="Delete" id="btntest" />
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("SUCCESS!!!");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
getSelectedChbox code
function getSelectedChbox(ele) {
var selchbox = []; array that will store the value of selected checkboxes
gets all the input tags in frm, and their number
var inpfields = ele.getElementsByTagName('input');
var nr_inpfields = inpfields.length;
traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
for(var i=0; i<nr_inpfields; i++) {
if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
selchbox = JSON.stringify({'selchbox' : selchbox});
}
return selchbox;
}
In the Controller, I’m performing a delete
What am I missing here?
Solution
You are using the id
binding (bind) event, which happens to be unique, so the click event will only apply to 1 element.
To resolve this issue, you can add a class to the delete
button. and iterate them to bind (bind) onclick
events.
HTML
<td class="td-org"><input type="button" value="Delete" class="delete-btn" />
JS
let btns = document.querySelectorAll('.delete-btn');
for(let i = 0; i < btns.length; i++) {
let btn= btns[i];
btn.onclick = function() {
your code
}
}
Alternatively, you can use a function in your script and onclick
in your HTML.
HTML
<td class="td-org"><input type="button" value="Delete" onclick="myFunction()" />
JS
function myFunction() {
your code
}