Unable to remove row from table created by jQuery - javascript

I am creating a table based on result from servlet, which contains a checkbox , when the checked property of checkbox is true there will be one button in the bottom of the table which calls for a remove function, which removes that particular row from table, this function is working when the table is created inside jsp using server tags, but when it is created from jQuery .getJSON method, it is not working. The code is.
var contents="";
$.getJSON("trnReceipt?caseNo=21&insid="+cdid.text(),function(datalist) {
$.each(datalist, function(index, data) {
contents += '<tr><td><input type="hidden" id="txt_select'+index+'" name="txt_select'+index+'" value='+data.return_status+'></input><input type="checkbox" name="chk_select'+index+'" /></td><td><input type="hidden" name="txtInstrid'+index+'" value="'+data.Instrumentid+'"/>' + data.Instrumentid + '</td></tr>';
index++;
})
$('#tblDetails').append(contents);
})
The Javascript code to delete the row is:
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) {
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e) {
alert(e);
}
}
Where I am making a mistake?

You can use jQuery to delete the rows like this:
$('#' + tableId + ' tr:has(td :checkbox:checked)').remove();
This will delete all rows that contain a checked checkbox.
Your problem is probably that you're looking in the wrong cell.

The first node in your td tag is the hidden field, not a checkbox. So, in the rows that come from the getJson method, the chkbox variable is not actually your checkbox, and hence the criteria for deleting the row will always be false.
As long as you're already using jQuery, consider using jQuery for the actual delete. It will be much shorter and actually less prone to errors.

Related

how to check box work in table for every row correctly?

The checkbox does not work for every row correctly why? How can I make it work?
I put full code here press on this link tried many times but it does not work.
function check(chk) {
var checkb = document.getElementById(chk);
if (checkb.checked == true) {
document.getElementById('textbox').value = "1234567";
$(".js-example-basic-multiple").prop("disabled", true);
} else {
document.getElementById('textbox').value = "0000000";
$(".js-example-basic-multiple").prop("disabled", false);
$(".js-example-basic-multiple").val(null).trigger('change');
}
}
var checkb = document.getElementById(chk.id)
checkb is coming back undefined because document.getElementById looks for an id value. You are passing chk which is the whole checkbox tag, attributes and all. chk.id gives you the id and ensures checkb is defined. You also need to change
document.getElementById('textbox').value = "1234567";
document.getElementById('textbox').value = "0000000";
to
document.getElementById('textbox1').value = "1234567";
document.getElementById('textbox1').value = "0000000";
because you set the ids this way with this line
var tBody = tBodyTemplate.replace(/textbox/g, 'textbox' + rowCount);
This works when you have just 1 row. When you add more, things break. You also need to make the id unique. chk1 can't be used as an id for each duplicated row. Ids should be unique
'<input type="checkbox" id="chk1" onclick="check(\chk1\)" >'
chk1 should be paired with textbox1.
chk2 should be paired with textbox2 and so on

JQuery td:contains

So at work, I have to go through a list that contains thousands of users and select a checkbox by the ones I need to delete. Long story short it's a slow process. To make things faster I made this script to run in chrome using developer tools in the console.
var usernames = ["jimmy123"];
for(var i=0;i<usernames.length;i++)
{
jQuery("td:containsExact("+usernames[i]")").find('[type=checkbox]').parent().attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
alert("Everything Returned Okay!");
alert(usernames.length);
alert(count + " Checkboxes Checked!");
The Trouble is that let's say a user created 3 because they forgot the login for them "not uncommon" and their username is:
jimmy123
jimmy1234
jimmy12345
If I need to just check the box next to jimmy123 for removal my script selects all 3 since they have mostly the same username.I tried some filters but the result was the same.
Backend Screenshot
You can use filter() function here to match the exact text in the td and then mark the checkbox selected. See the below script, you didn't provide the HTML so I added a sample table with some td containing usernames and checkbox, you should update the script accordingly
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("tr>td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="checkbox">omer</td>
<td><input type="checkbox">omer123</td>
<td><input type="checkbox">omer6565</td>
<td><input type="checkbox">omer63645</td>
<td><input type="checkbox">omer021</td>
<td><input type="checkbox">omer521</td>
<td><input type="checkbox">jimmy123</td>
</tr>
</table>
EDIT
You can assign an id to your table say my-table and then change the selector in the code above from
$("tr>td").filter(function() {
to the following
$("#my-table tr>td").filter(function() {
The exact selector could be suggested when you add the HTML for your user listings that you are using the script with.
EDIT2
According to your html it should be
$(function($) {
var usernames = ["jimmy123", "omer"];
for (var i = 0; i < usernames.length; i++) {
$("#listContainer_datatable tr td").filter(function() {
return $(this).text() == usernames[i]
}).find('[type=checkbox]').attr('checked', true).css("background-color", "red");
}
var count = jQuery("[type='checkbox']:checked").length;
console.log("Everything Returned Okay!");
console.log("usernames.length" + usernames.length, usernames);
console.log(count + " Checkboxes Checked!");
});

Javascript to evaluate contains method on a <tr> or the entire table

I have the following code and it works when there are rows in a table. however I need to add a contains logic where rowCount=0 if td contains "There are no items to show in this view".
https://jsfiddle.net/xnyLq1na/
var rowCount = $(".ms-WPBody tr").not(":has(th)").length;
if ($('.ms-WPBody tr >td:contains(there are no items)')
{
alert ("found it");
rowCount = 0;
}
$(".rowCount").text("Num of rows: " + rowCount);
changed the logic, fetching the html inside <a> tag and then comparing to see if it contains the required String.
you were missing a ) after ("there are no items")') too.
$(document).ready(function(){
var rowCount = $(".ms-WPBody tr").not(":has(th)").length;
var x = $('.ms-WPBody tr td a').html();
//alert(x.indexOf("there are no items"));
if(x.indexOf("There are no items") !== -1){
//alert ('found it');
rowCount = 0;
}
$(".rowCount").text("Num of rows: " + rowCount);
});
EDIT Update:- changed the logic, fetching the html inside <a> tag and then comparing to see if it contains the required String.
Fiddle here

Append a header to dynamically-loaded tables using JQuery

I've been having a hard time trying to append new headers to tables I build dynamically using data grabbed from an AJAX call.
I've already asked here a question about my problem, but it seems that there's no logical answer to it.
So my problem is that I can't actually get the table I want to append my new info to, what I tired was this:
console.log(id); //This prints the right id!
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
//$('#'+401+' tr:first').append("<td>Well "+(wellCounter)+"</td>");--this will work
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
But it didn't work, so I was wondering if you can help me with another way to get the same functionality without using the id to get the table. Maybe the closest function will work but I don't have experience with that, and I tried it but failed.
Here the full code:
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(index2, secondLevel) {
var id = firstLevel['id'];
var author = firstLevel['author'];
var date = firstLevel['date'];
var experimental_conditions = firstLevel['experimental_conditions'];
if(index2 == 'items'){
var table = '<div class=tableWrapper><table id=\"'+id+'\" class=\"experimentTable\">';
table += '<input id=\"basketButton\" type=\"submit\" value=\"Add to basket\" class=\"basketButton\" experimentBatch=\"'+id+'\"> <div class="superHeader"><span class=\"superHeader\">Date: '+date+', By '+author+'</span><br /><span class=\"subHeader\">Experimental conditions: '+experimental_conditions+'</span>'
table += '<tr><td></td><td COLSPAN=2>Totals</td></tr>';
table += '<tr id="header"><td width="20%">Genotype</td><td width="10%"><img src="images/herma.png"></td><td width="10%"><img src="images/male.png"></td>';
//for each table
$.each(secondLevel, function(index3, thirdLevel) {
var nWells = 0;
table += "<tr><td>"+thirdLevel['mutant_name_c']+"</td><td>"+thirdLevel['herm_total']+"</td><td>"+thirdLevel['male_total']+"</td>";
currentRow = 3;
wellCounter = 0;
//for each row
$.each(thirdLevel, function(index4, fourthLevel) {
wellCounter++;
if (fourthLevel.date_r != undefined){
console.log(id);
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
}
});
});
table +='</table></div>'
$('#searchResults').append(table);
}
});
});
NOTE: Male and herm are worm genders, not options!
I didn't go through your code, but when I'm working with dynamic table in jquery i try with Jquery "OBJECT". something like
var $tbl = $('<table />'), $tr=$('<tr />'), $td=$('<td />');
then you can add attr, append etc, and is much easier to read, and manipulate.
$tbl.attr('id',id).append($tr.append($td);
etc.

Dynamic content gets thrown out of a table

I have a problem while generating a list of live search results - I put them in a special div with id "result" the way below (dont mind the SightsList, this is an AJAX - pre-retrieved array; also the algorythm is not optimal, I know it, but that's not the subject). So the main issue is why table rows get thrown out of a table? Html in browser looks like <table></table><tr><td>(and then all the lines generated). The same problem goes with <ul> and <li>.
$("input#namebox").keyup(function() {
var value = $(this).val();
value = value.toLowerCase();
value = $.trim(value);
if (value.length > 3) {
$("#result").html("<table>");
for (var i=0; i<SightsList.length; i++) {
if (undefined != SightsList[i]) {
if (void 0 != SightsList[i]) {
SightsList[i] = SightsList[i].toLowerCase();
if (SightsList[i].indexOf(value)+1) {
$("#result").append('<tr><td class="singleresult" valign="middle">' + SightsList[i]+ ' – ' + '<img src="/images/balloon.gif" rel="'+ i +'" class="balloon_img" /></td></tr>');
$("#message").show();
}
}
}
if (i==(SightsList.length-1)) {
$("#result").append("</table>");
}
}
//tried to close table here with the same (no) result $('.singleresult').highlight(value);
$("#result").show();
}
if (value.length < 4) {
$("#result").hide();
$("#result").html("");
}
}
.html and .append aren't just string functions, they work on the DOM.
$("#result").html("<table>") places a table in the #result element. Since there are no rows specified, it is an empty table (<table></table>). Then your .append tries to put a row after that table.
So instead of appending to the contents of #result, you want to append to the table you are creating:
$("#result > table").append('<tr><td class="singleresult" valign="middle">' + SightsList[i]+ ' ' + '<img src="/images/balloon.gif" rel="'+ i +'" class="balloon_img" /></td></tr>');
and remove your attempt to add an end-table tag.

Categories

Resources