JQuery td:contains - javascript

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!");
});

Related

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

Get the Checked and Unchecked table data via jquery

I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});

Remove particular row of text in string based on id selected

I am trying to remove a certain table row in a string. For instance, I have the code below in a string. Lets call the variable that stores the string below temp
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
I have several buttons with id's corresponding to the number of row above. If I click the first button it has a corresponding id of 1, the second button has 2, etc.
What I am getting at is that if I hit these delete buttons, I want to remove the corresponding table row above based on what id (button) I click.
Here is my code so far.
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).closest('tr').remove();
}
How would I delete a part of that string in my variable temp based off of the id(button) I click? If I choose button 1, I want to delete the first table row. Button two, second table row, etc. I know I need to replace the string, but how do I remove certain instances within the string?
Parsing HTML is dangerous. Therefore I suggest you convert your string to DOM and then manipulate on the DOM tree.
Here is a simple solution with jQuery:
var row = 1; // the row I want to remove
var temp = $("#myTextarea").value(); // get HTML
var table = $("<tbody>" + temp + "<tbody>"); // creates DOM nodes from HTML
table.find("tr").eq(row - 1).remove();
var tempWithoutRow = table[0].innerHTML;
Try yourself in JSFiddle.
You are trying to use jQuery as if that elements are in DOM... and they are not. They are just one string. So you can do something like that:
var arr = yourString.split("<tr>");
$(".delete").click(function() {
var id = $(this).attr("id");
arr = arr.splice(parceInt(id, 10)-1, 1);
}
Now you have array with the right TRs inside. All you have to do is to convert them to string again:
var htmlString;
for (var i=0; i<arr.length; i++) {
htmlString += arr[i];
}
UPDATE jQuery WAY
You can do it with jQuery too. Look at the fiddle
http://jsfiddle.net/J6HJ2/2/
You can select all the table rows and then filter down to the one you want:
$(".delete").click(function() {
var id = $(this).attr("id");
$("#my-table").find("tr").eq(id + 1).remove();//since your IDs are not zero-indexed and .eq() is
});
Docs for .eq(): http://api.jquery.com/eq
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).parentNode.remove();
}
if the .delete is on the td
else if u have <td><button class="delete"></button></td>
then it's $(this).parentNode.parentNode.remove();
no need for the id if the button is inside the <tr>
Easy solution would be to give the rows meaningful ID's and use the following code:
$(".delete").click(function() {
$('#row' + $(this).id).remove();
}
If you really want to count nameless TR elements in a string you could split them into an array with split("<tr>")

Jquery group by td with same class

I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.

Unable to remove row from table created by jQuery

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.

Categories

Resources