jQuery search through table rows, hidden and visible - javascript

I've got a table where i display message history. By default the table displays only the last message between two people. But all of the messages are in the HTML code, just that they are set with display:none;
Im trying to make the search go through both visible and hidden tr rows.
What i currently have:
HTML:
<table cellpadding="0" cellspacing="0" width="100%" class="tDefault mytasks" id="history">
<tr>
<td>Finish design</td>
<td align="center"><strong class="grey">0%</strong></td>
</tr>
<tr>
<td>Aquincum HTML code</td>
<td align="center"><strong class="green">89%</strong></td>
</tr>
<tr style="display:none;">
<td>Aquincum cpp code</td>
<td align="center"><strong class="green">99%</strong></td>
</tr>
<tr>
<td>Fix buggy css styles</td>
<td align="center"><strong class="red">16%</strong></td>
</tr>
</table>
jQuery:
$("#search").keyup(function() {
var value = this.value.toLowerCase().trim();
$("#history tr").each(function (index) {
if (!index) return;
$(this).find("td").each(function () {
var id = $(this).text().toLowerCase().trim();
var not_found = (id.indexOf(value) == -1);
$(this).closest('tr').toggle(!not_found);
return not_found;
});
});
});
I have two problems:
For some reason the first tr is always visible even through it does not match the search. Try to search for buggy css. You'll see that the first tr is still there.
When i search for something, and then clear the search field. The second tr which is by default set to display:none; is visible. It has to somehow go back to a display:none state
jsfiddle:
http://jsfiddle.net/2T5yJ/

For first row index is zero. So its not reaching
$(this).find("td").each(function () {
Remove
if (!index) return;
And search filter would work correct
Update you can check if value="" and write logic to get back display of rows to original
Please check updated fiddle
FIDDLE

Related

Delete table rows if table data does not contain a specific class

I got a question regarding removing table rows within a table. I got the following HTML:
<table>
<tr>
<td class="html5badge">autofocus</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
<tr>
<td>disabled</td>
<td>disabled</td>
<td>Specifies that a drop-down list should be disabled</td>
</tr>
<tr>
<td class="html5badge">test</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
</table>
I need a mechanism that looks whether the first <td> does not contain the html5badge class and delete the parent: <tr>.
To do this I created the following jQuery code:
$(document).ready(function() {
$(".onlyhtml5").click(function(event) {
event.preventDefault();
var classname = $('table tr td').not('.html5badge');
console.log(classname)
for (i = 0; i < classname.length; i++) {
$(classname[i].parentNode).remove();
}
});
});
This works but it does not exactly what I want. As you can see in my JSFIDDLE it will delete all the table rows. But what I want is the following desired output:
<table>
<tr>
<td class="html5badge">autofocus</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
<tr>
<td class="html5badge">test</td>
<td>autofocus</td>
<td>Specifies that the drop-down list should automatically get focus when the page loads</td>
</tr>
</table>
The desired output is that the <tr> that contained the text: disabled is been removed! Based on the fact that the <td> within this <tr> does not contained the class: html5badge.
How can I achieve this?
You can use filter() to retrieve the tr elements which do not contain td.html5badge and remove them:
$(".onlyhtml5").click(function(e) {
e.preventDefault();
$('tr').filter(function() {
return $(this).find('td.html5badge').length == 0;
}).remove();
});
Updated fiddle
simply make it
$(document).ready(function() {
$(".onlyhtml5").click(function(event) {
event.preventDefault();
$('table tr td').not('.html5badge').each( funtion(){
$( this ).parent().remove();
} );
});
});

jQuery Select Checkbox When Text Exists, Hide Unselected Rows from Print

I have a dynamically generated table that contains a checkbox for each row, some data, and a text input field.
I want to automatically check the checkbox for a selected row once text is entered in that row's textbox. Finally, when the 'Finish' button is pressed, I want any unselected rows to be hidden from printing. Final output will be the table containing only the selected rows (i.e. those with a check in the checkbox) and their values.
Here's the css print class to hide the unselected rows:
<style type="text/css" media="print">
.grid .hidden tr {
display:none;
}
</style>
Here's the HTML:
<table id="data" class="grid">
<thead>
<tr>
<th> </th>
<th>Part Number</th>
<th>Description</th>
<th>Qty to Order</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="check"></td>
<td>1234</td>
<td>Description data goes here</td>
<td><input type="text" class="inputData"></td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>3454</td>
<td>Description data goes here</td>
<td><input type="text" class="inputData"></td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>6787</td>
<td>Description data goes here</td>
<td><input type="text" class="inputData"></td>
</tr>
</tbody>
</table>
<button id="clicker">Finish</button>
Finally, here's the jQuery. This is selecting all the checkboxes when text is entered in a text field, not just the one for that row (which I don't understand), and not assigning the "hidden" class to the rows without a checkbox - the class is not being assigned at all.
$(document).ready(function() {
//Check for input in text field
$('#data > tbody > tr').each(function() {
$(".inputData").change(function() {
if ($(this).val().length > 0) {
$(".check").prop("checked",true);
} else {
$("tr").addClass("hidden");
}
});
});
$("#clicker").click(function() {
window.print();
return false;
});
});
</script>
My logic in constructing this was to make sure we're only selecting rows in the table with an id of data. The first function will iterate over each row looking at the text field, and if the length of that field is greater than 0, check the box. Otherwise, assign the class of "hidden", which will prevent it from printing. Finally, simply assign a click event to the button.
Any help is greatly appreciated.
Here's a jsFiddle
This checks or unchecks the appropriate box based on whether the input has a value:
$(".inputData").on('input', function () {
var checkbox= $(this).closest('tr').find('[type="checkbox"]');
checkbox.prop('checked', $(this).val());
});
It doesn't need to be within an each() method.
This hides all rows in which the checkboxes are not checked:
$('[type="checkbox"]:not(:checked)').closest('tr').hide();
It makes sense to put that within the $("#clicker").click() function.
Updated Fiddle

Multiple elements with same Id in Javascript

I have a case where a html file contains multiple elements with the same ID name.
The table row contains 5 columns of which I need to consider 2,3,4,5 columns data.
<tr id='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
I have the above code at several places in the file. I need to add the respective values using javascript.
An ID is unique in an html page. You can call it THE ID as well wrt a page. You cannot have same ID for two different tags in a single page. But you can use class instead of and ID. Know about it here
So your HTML can be like
<tr class='total_row'>
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
As an example with jquery you can do something like this,
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<table>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
<tr class="one">
<td></td>
<td></td>
</tr>
</table>
<script src="jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$(".one").eq(0).find('td').eq(0).html("I'm tracked");
// get 1st tr and get first td
$(".one").eq(1).find('td').eq(1).html("I'm tracked");
// get 2nd tr and get second td
$(".one").eq(2).find('td').eq(0).html("I'm tracked");
// get 3rd tr and get first td
});
</script>
</body>
</html>
But I guess this approach can be tedious.
Id should be unique and if you use the same id, javascript code refers only the first element. but if you still want to use same id than you may try the below code:
$(function(){
$('[id="total_row"]').each(function(){//run for every element having 'total_row' id
var $this = $(this);
$this.find('td').eq(1).text() //to get second column data
$this.find('td').eq(1).text('dummy text') //to set second column data
});
});
You can use XHTML:
<p id="foo" xml:id="bar">
Through XHTML you can apply similar ID to multiple Controls.
Similar questions can be found here:
http://www.c-sharpcorner.com/Forums/
While duplicate IDs are invalid, they are tolerated and can be worked around. They are really only an issue when using document.getElementById.
I'll guess that the table looks like:
<table id="t0">
<tr>
<td>-<th>count<th>Pass<td>Fail<td>Error<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
<tr>
<td>-<td>1<td>1<td>0<td>0<td>
<tr>
<td>-<td>1<td><td>1<td>0<td>
<tr>
<td>-<td>1<td><td>0<td>1<td>
<tr id='total_row'>
<td>Total<td><td><td><td><td>
</table>
<button onclick="calcTotals();">Calc totals</button>
If that's correct, then a function to add each sub–section can be like:
function calcTotals(){
var table = document.getElementById('t0');
var rows = table.rows;
var row, totals = [0,0,0,0];
// For every row in the table (skipping the header row)
for (var i=1, iLen=rows.length; i<iLen; i++) {
row = rows[i];
// If it's a total row, write the totals and
// reset the totals array
if (row.id == 'total_row') {
for (var j=0, jLen=totals.length; j<jLen; j++) {
row.cells[j+1].innerHTML = totals[j];
totals[j] = 0;
}
// Otherwise, add values to the totals
} else {
for (var k=0, kLen=totals.length; k<kLen; k++) {
totals[k] += parseInt(row.cells[k + 1].innerHTML) || 0;
}
}
}
}
In addition to using classes, which works but feels kind of icky to me, one can also use data-* attributes.
<tr class='total_row' data-val-row-type="totals-row">
<td>Total</td>
<td>%(count)s</td>
<td>%(Pass)s</td>
<td>%(fail)s</td>
<td>%(error)s</td>
<td> </td>
</tr>
Then, in your script (jQuery syntax -- querySelectorAll has a similar syntax)
var $totalsRows = $("[data-val-row-type='totals-row']);
When you are in a team with a separate UI designer, this keeps the UI guy from ripping out and changing your class names to fix the new design layout and it makes it quite clear that you are using this value to identify the row, not just style it.

Need to delete row if checkbox is checked

I've got a jQuery/AJAX solution set up to update and delete items that are displayed in a table. The AJAX part works fine but once an item is deleted I need to be able to remove it from view and I can't figure out how to identify the selected item(s) based on their value after the submit button is clicked.
Here's my jQuery:
$('#button').click(function(event){
var order = $("#sortable tbody").sortable("serialize");
order += "&" + $("form[name=favorites]").serialize().replace(/%5B%5D/g, '[]');
order += "&crudtype=update_favorites";
$('#savemessage').html('<p>Saving changes...</p>');
$.post("/crud",order,function(theResponse){
$('#savemessage').html(theResponse);
});
});
});
My HTML is generated from PHP so the quantities and IDs are variable but the format is as follows:
<tr class="odd" id="field_37">
<td class="handle">Item #1 Name</td>
<td><input type="checkbox" name="fid[]" id="fid" value="37" class="box check-child"></td>
</tr>
<tr class="even" id="field_29">
<td class="handle">Item #2 Name</td>
<td><input type="checkbox" name="fid[]" id="fid" value="29" class="box check-child"></td>
</tr>
So effectively what (I think) I need is to add to my .click function something like "foreach checked fid, remove the corresponding row ID" if that makes any sense.
A basic selector to get a checked checkbox is
'input[type="checkbox"]:checked'
or
'input:checkbox:checked'
Now you can either use has() or loop through and use closest to get the trs
$('input[type="checkbox"]:checked').closest("tr").remove();
or
$('tr:has(input[type="checkbox"]:checked)').remove();
You can do it like this: http://jsfiddle.net/dSANw/
When user clicks on checked box add class to the parent tr
$(".box").click(function() {
if($(this).is(':checked')) {
$(this).parents('tr').addClass('checkedtd');
} else {
$(this).parents('tr').removeClass('checkedtd');
}
});
When clicked on delete, get all tables tr's classed 'checkedtd' and delete
$("#delt").click(function() {
alert($('.checkedtd').length);
$('.checkedtd').remove();
});

On button click, validate that atleast a row must be moved to a custom table with Jquery

I am using MVC3, EF Model first on my project.
I have a view with 4 tables and then I have a CustomPickedTable, whenever a user click on a row inside those 4 tables that row moves to CustomPickedTable Table this is the code for it:
<script type="text/javascript">
$(function () {
$('.questionsForSubjectType tbody tr').click(function () {
var origin = $(this).closest('table').attr('id');
$(this)
.appendTo('#CustomPickedTable tbody')
.click({ origin: origin }, function (evt) {
$(this).appendTo('#' + evt.data.origin);
});
});
});
</script>
What I am looking for is some kind of validation that when a user clicks on the submit button there should be a rule that make sures that atleast one row in each of those 4 tables must be moved to CustomPickedTable if not it should not post the form but give the user an errormessage.
This is one of my 4 tables, these get generated by a foreach loop with razor in MVC
<div class="questionsForSubjectType" id="questionsForSubjectType_1">
<table class="box-style2" id="RandomID_c5b9bc7a-2a51-4fe5-bd3a-75b4b3934ade">
<thead>
<tr>
<th>
Kompetens
</th>
</tr>
</thead>
<tbody>
<tr>
<td data-question-id="16">Har konsulten Förmåga att lära sig nytt?</td>
</tr>
</tbody>
<tbody>
<tr>
<td data-question-id="17">Har konsulten rätt kompetens?</td>
</tr>
</tbody>
</table>
</div>
My custom table:
<table id="CustomPickedTable" class="box-style2">
<thead><tr><th>Choosen Questions</th></tr></thead>
<tbody>
</tbody>
</table>
Thanks in advance!
There might be a better way.
But i would add a data-attribute or some class to each of the TD's you can move, and on submit check for each required value.
Created an example here: http://jsfiddle.net/y35Qf/1/
Basicly i added an attribute called data-row, and each table has its own value, on submit i require each of these values to be in the CustomPickedTable - if not i alert that something is missing - else alert success.
You could easily add so you alert which rows are misssing or any other validation you would want.
Is this what you wanted?

Categories