I have encountered this code
$("#search").keyup(function(){
var val = $.trim(this.value).toLowerCase();
$("table > tbody > tr:gt(0) ").hide();
if(val.length){
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
} else $("table > tbody > tr:gt(0)").show();
});
For Querying a a table in jQuery. here's the HTML markup
<p>
<input id = "search" type = "text">
</p>
<table id ="accounts">
<tr>
<th>Username</th>
<th>Password</th>
</tr>
<tr>
<td>Metasm</td>
<td>password1992</td>
</tr>
<tr>
<td>superadmin</td>
<td>adminpassword</td>
</tr>
<tr>
td>skyrocketeer</td>
<td>thejetsons</td>
</tr>
</table>
Basically it works. but the I am very confused with regards to the jQuery code.
My Question: in this part of code
$("table > tbody > tr:gt(0) > td").filter(function(){
return this.innerHTML.toLowerCase().indexOf(val) >=0;
}).parent().show();
What does this part specifically do? and what does it return?
$("table > tbody > tr:gt(0) > td") - This lines of code states that you want all <td> elements within a <table> element that are in a <tbody> element, who's <tr> element's index is greater than 0 (ie - skip the first row. gt() is simple Greater Than). The > selector states that we only want elements in the first level of children - we don't want to drill down further than the first set of child elements.
The .filter() function will reduce the set of matched elements to those that match the selector or pass the function's test.
The conditional statement here is looking for a certain index of a search string val, within the innerHTML of each element.
this.innerHTML.toLowerCase().indexOf(val) >=0
So what this is saying (remembering that we are iterating over all the elements we found from our first selector) is that we are looking for an occurance of the string val within the innerHTML of the element. The innerHTML is also being passed through the toLowerCase() function, who's name suggests is function - converts all characters to their lowercase form.
Phew...Now after all this we are left with a certain list of elements. Elements that met all of our specifications above. For each of these elements, the code will locate their parent (remember we are talking about <td> elements, so their parents should be <tr>) with the .parent() function and display them on screen with the .show() function.
For the first selector - $("table > tbody > tr:gt(0) > td"), I find sometimes its easier to read it backwards (in your mind) to understand the hierarchy...
Return the -
I'm looking for <td> elements,
that are inside <tr> elements (but not the first one),
that are inside a <tbody> element
that all reside within a <table> element.
Now for some sample input and output.
Given the value of val is "jet", the function would display the last <tr> - the one with the string - thejetsons.
Given the value of val is "password", the function would display the two <tr> elements in the middle. The ones that contain "password1992" and "adminpassword".
I hope this sheds some light on your problem!
$("table > tbody > tr:gt(0) > td") will select all td inside tr:gt(0)... this is a basic jquery selector.
With those td selected, apply a filter based on returned value of the function, if return true, the td will be select.
Then your function: return this.innerHTML.toLowerCase().indexOf(val) >=0 means if the td contains a string (val) will return true, otherwise.
All of this equal to
$("table > tbody > tr:gt(0) > td:contains('"+val+"')").parent().show();
This code select all td elements in all tr elements except first one, then we execute the function for each element as context, if for element the function return false, then it is excluded from jquery 'array', then for all filtered elements we get tr elements in which they are and show them. Into the function we get inner text and search it in search query.
Related
I need in table change td when i click the button. I'm begginner in Jquery. I think to use this document.createTextNode In order to change the code in the table
.
Since I am a beginner, this will be correct or some differently correctly. Because table is so long and too code more
It's Example many code in Jquery (Screnshot)
$(".price-btn_1").click(function() {
$( "td:eq(2)").empty().append(document.createTextNode("123") );
$( "td:eq(3)").empty().append(document.createTextNode("456") );
});
> when .price-btn_2 click change text in table td
$(".price-btn_2").click(function() {
$( "td:eq(2)").empty().append(document.createTextNode("50") );
$( "td:eq(3)").empty().append(document.createTextNode("30") )
});
.price-table tr td{
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="price-btn_all price-btn_1 active">iPhone 4</button>
<button class="price-btn_all price-btn_2">iPhone 4s</button>
<table class="price-table">
<thead>
<tr>
<td>bla1</td>
<td>bla2</td>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>456</td>
</tr>
</tbody>
</table>
Thanks!
With jQuery it is way more easy to accomplish your goal. Since you only want to set the text in the table cells, just use text("123") on the selection:
$("td:eq(2)").text("123");
http://api.jquery.com/text/
I must say that getting the tds just by their number in the document order is no good design. What if you decide to add another table before the first one? You would have to adjust all the numbers in your source code. Better use ids instead.
Concept:
Store your texts in a 2-dimensional array (2d array)
Loop through each td and set their text according to the index
// keep the texts here
var data = [
['table0#data0', 'table0#data1', 'table0#data2', 'table0#data3'],
['table1#data0', 'table1#data1', 'table1#data2', 'table1#data3'],
];
$(".price-btn_1").click(function() {
// loop through each <td>
$(".price-table tbody td").each(function(n, el){
// data[0] means table1
// data[0][n] means nth data of table 1
$(el).html(data[0][n]);
});
});
$(".price-btn_2").click(function() {
// loop through each <td>
$(".price-table tbody td").each(function(n, el){
// data[1] means table2
// data[1][n] means nth data of table 2
$(el).html(data[1][n]);
});
});
jsbin snippet
Additional:
You don't really need to use .empty().append() when .html() does exactly the same thing. (If you're concern about performance, I don't think the difference could be noticeable)
Selecting by only $("td") could be dangerous, imagine you have two tables on your page.
Read more:
.each() method jquery
javascript array
I am trying to return an array of values for the first <td> of every <tr> within <tbody> of my table.
A demo here (attempt, not working) http://jsfiddle.net/vJqeT/1/
My JS Code:
var newArray = $('#table1 tr:first td').map(function() {
return $(this).html();
});
My expected result in my demo is:
[A, 1]
target all TR's, and then all TD's that are the first child of a TR, then get the trimmed text :
var newArray = $.map($('#table1 tr td:first-child'), function (el) {
return $.trim( $(el).text() );
});
FIDDLE
A few things (fiddle):
You've targeted tr:first so any subsequent rows are ignored.
You should be targeting cells rather than rows.
jQuery's :first selector is easily confused with :first-child. Unfortunately, :first returns only one item. Use :first-child instead.
or :first-of-type if you're expecting mixed td/th within the same row.
Call toArray() so you get a plain array.
var newArray = $('#table1 td:first-child span').map(function () {
return $(this).html();
}).toArray();
console.log(newArray);
I'm trying to find if a table contains only spaces in each columns. Practically it's an empty table but with spaces. Is it possible with Javascript or jQuery?
<table>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
Yes you can
$("table tr td").text().trim()==""
OR
$("table tr td:empty")
And if you want to do something like hide a the table based on the td emptiness, etc, refer to this post
Another fiddle example
Not a clear question, try this :
$('td').filter(function(){
return $(this).text().search(/^\s*$/) != -1;
}).doWhatYouWantWithThat()
You can use text() and trim() combination, if the trim() give zero length and without trim the length of text is not zero it means table contains spaces.
if($('#tableId').text().length > 0 && $('#tableId').text().trim().length == 0)
{
alert("Empty table with spaces.")
}
I'd suggest:
var cells = $('td'),
allCellsEmpty = cells.length == cells.filter(function(){
return $.trim($(this).text()) == '';
}).length;
JS Fiddle demo.
To hide the table, if its child td elements have no content (other than white-sapce):
$('table').toggle(!allCellsEmpty);
JS Fiddle demo.
References:
filter().
jQuery.trim().
text().
When triggered, the 3rd (bottom) row of a table is cloned. In the CSS, this row (#tr3) is set to: display:none; Here is the table row I am cloning:
<tr name="tr3" id="tr3">
<td><input type="text" name="dt1" id="dt1"></td>
<td><input type="text" name="fn1" id="fn1"></td>
<td>change</td>
<td>delete</td>
</tr>
This is the JQuery code to clone the row. Not mine, sadly, so I don't understand all of it.
$("table tr:nth-child(4)").clone().find("input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
Specifically, how does the function in line 2 work - what is the underscore?
Here's what I came for, though. How can I:
change the style to display:block for cloned rows, and
update the ids of the anchor tags in the cloned rows. The IDs of the input fields Do update (e.g. fn1 => fn11, fn12, fn13, fn14, etc).
Thank you.
Just for clarity:
var $clone = $("table tr:nth-child(4)").clone();
How to change the style to display:block for cloned rows?
$clone.show();
How to update the ids of the anchor tags in the cloned rows.
$clone.find("a, input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
});
In the jQuery code above, how does the function in line 2 work - what is the underscore?
The underscore (_) is a valid ECMAScript's identifier name and it is used simply as a placeholder to be able to grab the second argument (id.)
And everything altogether (untested.)
$("table tr:nth-child(4)")
.clone()
.show()
.find("a, input").each(function() {
$(this).val('').attr('id', function(_, id) {
return id + count;
});
});
You never actually access the cloned row on its own. You would have to assign it to something, e.g.
$clonedRow = $("table ...").clone();
then you can run all of the other methods and finally append $clonedRow to the DOM, possibly with
$clonedRow.insertAfter("table ...")
You need to somehow strip off the last digit(s), possibly with a regex:
return id.replace(/\d+$/, '') + count;
The _ is just a placeholder. It's not used, so the writer of the code chose a nondescript variable name since something is required in the declaration to get at the id parameter.
What is a good way to find the index of column by it's display text?
e.g.
<table>
<tr>
<td>ID</td>
<td>Name</td>
<td>Age</td>
</tr>
<tr>
...
</tr>
</table>
I would like to have something like
var nameIndex = getColIndex('Name'); // nameIndex = 1
Is there a quick / good way to do it? (Doesn't have to be jQuery, but would be nice)
The following both seem to work, in Chromium 17/Ubuntu 11.04:
$('tr td').filter(
function(){
return $(this).text() == 'Name';
}).index();
JS Fiddle demo.
Or:
$('td:contains("Name")').index();
JS Fiddle demo.
Edited in response to OP's question, in comments, below:
but how do I limit it to the first row?
To limit it to the first row, simply use the :first selector:
$('tr:first td')
Giving:
$('tr:first td').filter(
function(){
return $(this).text() == 'Name';
}).index();
JS Fiddle demo.
References:
:contains().
filter().
:first.
//select the first TR element, then select its children (the TDs),
//then filter them down to only the one that contains a certain string
var theIndex = $('tr').first().children().filter(function () {
return ($(this).text() == 'ID');
}).index();
When passing .filter() a function, if you return true for an index, then it will be kept in the selection, and if you return false then that index will be removed from the selection: http://api.jquery.com/filter
This will limit the search to the first row and give the index of the column with the specified search text (this code used ID).
Note that .index(), when used like above, will return the index of the current selection based on its sibling elements: http://api.jquery.com/index
http://jsfiddle.net/justiceerolin/FdhcV/
$(function(){
$('#search').click(function(){
$('td').each(function(index){
if ($(this).text() == $('#lookup').val()){
console.log(index)
}
});
});
});