Add element to passed jQuery selector - javascript

I'm trying to pass a table to a function and then get the rows using jQuery. What am I doing wrong here?
sortTable($('#myTable'));
function sortTable(targetTable)
{
var rows = $(targetTable + ' tr');
}
Error: Uncaught Error: Syntax error, unrecognized expression: [object Object].tr

I think the problem is here:
sortTable($('#myTable'));
You're passing targetTable a jQuery object, so adding it to a string forces it to turn into a string, which is [object Object]. I think you mean:
sortTable('#myTable');
function sortTable(targetTableSelector) {
var rows = $(targetTableSelector+ ' tr');
}

You can use .find():
var rows = targetTable.find("tr");
That will find all the <tr> elements starting from the table and give you a new jQuery object containing them.
You can get the selector that was used to construct a jQuery object:
var tableSelector = targetTable.selector;
In this case that'd be the string "#myTable". However, jQuery objects are not always formed from selectors. If you obtain a reference to the table DOM node via something like an event handler, there won't be a selector. You can still use .find() to locate elements from a "starting point" jQuery object.
Note that .find() does its work for all the elements in the starting jQuery collection. If your initial object was a collection including two <table> elements, then .find("tr") would find all the rows under both tables.

Method one, passing jQuery object:
sortTable($('#myTable'));
function sortTable(table) {
var rows = table.find('> tbody > tr');
}
Method two, passing selector string:
sortTable('#myTable');
function sortTable(tableSelector) {
var rows = $(tableSelector).find('> tbody > tr');
}
Edit: (assuming you want only the rows within the tbody and not the head, otherwise remove "> tbody > tr")

Your passing in a jQuery object. Not the id. This means that when you concatenate your id to your targetTable argument you'll get:
[object Object] tr
Thus you'll be trying to select:
$("[object Object] tr")
Which isn't what you want. Instead, you need to pass in the table id into your function so that you concatenate it with a string, rather than an object.
See working example below:
function sortTable(targetTable) {
var rows = $(targetTable + ' tr').toArray();
return rows.toArray();
}
console.log(sortTable('#myTable'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" border=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Bob</td>
<td>23</td>
</tr>
<tr>
<td>John</td>
<td>33</td>
</tr>
</table>

Related

Filter Table with JQuery using the “each” element

OK everybody, I hope you can help me. I have a problem with JQuery or better with the each selector of JQuery.
I have an example table, where I want to filter for special values which I entered before. Those values I got from my input field , store them in a variable, split the data an create an JQuery Object.
Well and then I think I have a problem with the selection, marked in the code section.
<p>
<input id="testyear" size="4" type="text">
<input value="Werte" onclick="getvalue()" type="button">
</p>
<script>
function getvalue() {
var wert = $('#testyear').val();
$("#years").find("tr").hide();
var data = this.value.split(" ");
// create jQuery Object
var jQueryObject = $("#years").find("tr");
// i think here is my error, i want to display only the object which are equal or better stored in my variable “wert”.
$.each(data, function (){
//jQueryObject = jQueryObject.filter(wert);
jQueryObject == wert;
});
jQueryObject.show();
};
<!--Example Table-->
<table id="years">
<tbody>
<tr>
<td>1997</td>
<td class="century">20</td>
</tr>
<tr>
<td>2001</td>
<td class="century">21</td>
</tr>
</tbody>
</table>
I expect, that when I enter 1997 in the inpt field, the whole tr which contains 1997 will be displayed. I know it is simple but I have no idea so thanks for your help.
Use a filter on the TR's after initially hiding them all.
e.g.
getvalue = function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
};
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/
Notes:
The ~~ is a little conversion to integer trick
You seem to have extra code you do not need in the example
Just get filter to return true for each item you want to keep and false for the rest
When using jQuery, avoid using inline event handlers (like onclick=). Use jQuery event handlers instead. See below:
e.g.
$('#wert').click(function() {
var wert = $('#testyear').val();
// create jQuery Object
$("#years tr").hide().filter(function() {
return ~~$("td", this).first().text() >= wert;
}).show();
});
JSFiddle: https://jsfiddle.net/TrueBlueAussie/h8Lejfac/1/
I think your problem is not in each() method (not selector). Your problem is here:
var data = this.value.split(" ");
this is not defined (you are not in an object scope). I think you need this:
var data = wert.split(" ");
-----------^^^^
You've obtain the value of wert in the last line.

Get td parent and tr child

I need to get the value "TEST1" from the first TD clicking on the button. I tried the Javascript but it doesn't work.. The print gave me undefined.
<table style="width:100%">
<tr>
<td>TEST1</td>
<td>TEST2</td>
<td><button class='x' type='button' onclick='openindex()' >value='button'</button></td>
</tr>
</table>
Here is my Javascript function, I can't figure out what I'm doing wrong because I find the closest Tr but the child property doesn't work
function openindex(){
var $row = $(this).closest("tr");
$tds = $row.find("td:nth-child(1)").value;
alert($tds);
}
You are calling openindex() without an explicitly context, so this (inside it) will be window and not the element.
You could pass it:
onclick="openindex.call(this)"
but you should avoid using onclick attributes in the first place and bind your functions with jQuery().on instead.
jQuery('button').on('click', openindex);
I think you just need to use
$tds = $row.find("td:nth-child(1)").text();
instead of
$tds = $row.find("td:nth-child(1)").value;
You should also use the var keyword to set the variable so it is not a global variable and since it is just returning a string there is no need for the $ so
var tds = $row.find("td:nth-child(1)").text();
Or another way altogether would be
$('.x').click(function () {
var $row = $(this).closest("tr");
var tds = $row.find('td').first().text();
alert(tds);
})

get jsonArray from table

I have a table and need to build json array. I need value from 1 and 4 column of table.
HTML
<table class="table table-striped" id="development_mapping">
<thead>
<tr>
<th>Visual Feature</th>
<th>Step</th>
<th>Output</th>
<th>Data Feature</th>
</tr>
</thead>
<tbody>
<tr><td>color</td>
<td><select id="sss"><option data-id="528092be144b4fbf65893404" selected="selected">first-step</option><option data-id="52809373144b4fbf6589340c">kmeans</option></select></td>
<td><select id="ooo"><option data-id="output" selected="selected">output</option></select></td>
<td><input id="value1" class="feature-execution"value="id"></td></tr></tbody>
</table>
Here is my solution, a function to made an json array from table
JAVASCRIPT
var jsonArray = {};
$('#development_mapping').find('tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
I have done, but not understand, why I get " " from value of 4 column. I mean, why variable in variable is always getting " "
This is my DEMO
Your selector: $('#development_mapping').find('tr') is selecting all <tr> tags in the table. Even the one in the <thead>! The <thead> doesn't have <td> tags, so that's where the " " is coming from.
Try this:
$('#development_mapping').find('tbody tr').each(function () {
var name = $(this).find('td:first').text();
jsonArray[name] = {
variable : $(this).find('td:eq(3)').text()
};
});
You are using .text() but there is no actual text in your 3rd td tag.
try this maybe?
variable : $(this).find('td:eq(3) input').val()
There are 2 problems with your code.
Remove the surrounding <tr> in your table head definition.
Use this to access input value
variable: $(this).find('td:eq(3) > input').first().val()
$.find() will return a collection and you'll need to get the first object of the collection for further use. Plus, you'll need to search for input inside the cell, not the cell itself.
Here is the working fiddle: http://jsfiddle.net/toshkaexe/7q3KP/

How do I reference a table row using jQuery

Afternoon,
I wish to pass the row number of a table to a function to reference that specific row in that specific table, for example say I have this:
<table id="foo">
<tr><td>some stuff...</td><tr>
<tr><td>stuff</td><tr>
<tr><td>more stuff</td><tr>
<tr><td>some stuff</td><tr>
<tr><td>some stuff</td><tr>
</table>
and I have looped through the table rows and obtained the index, so in this example say I wanted to do something with the third row (which would have an index of 2, the one which has the contents "more stuff"). And I passed this through a function, like this
manipulateRow(2)
and this is my whole function
function manipulateRow(rowIndex){
/* do something */
}
How do you refer the rowIndex parameter to the table within the function? For example:
$('#foo').child("tr")[rowIndex].html('<td>i now contain even more stuff!</td>'); // I know this is wrong, how do I make it right?
Sorry if I'm being a bit thick or not explaining myself.
Easy.
$("#foo tr:eq("+rowIndex+")").html("<td>i now contain even more stuff!</td>");
Learn more about jQuery selectors here: http://api.jquery.com/category/selectors/
that could work actually only like this:
$($('#foo tr')[rowIndex]).html('<td>i now contain even more stuff!</td>');
but best to use :eq
Try this
$('#foo > tr').eq(rowIndex).html('<td>i now contain even more stuff!</td>');
function manipulateRow(rowIndex) {
var $row = $('#foo tr:nth-child(' + rowIndex + ')');
...
}
See nth-child-selector.
here you go:
<table>
<tbody>
<tr><td>Foo</td></tr>
</tbody>
<tfoot>
<tr><td>footer information</td></tr>
</tfoot>
</table>
$("#myTable > tbody").append("<tr><td>row content</td></tr>");
heres another example inline editing:
function editRow(row) {
$('td',row).each(function() {
$(this).html('<input type="text" value="' + $(this).html() + '" />');
});
}

take values from table cells and turn into array

using jquery I need to retrieve an array from table cells, format the data and pass it into a js function.
the code i am using is this:
var l1 = new Array();
$('table#datatable tbody td:first-child').each(function() {
l1.push($(this).text());
});
this is the table fragment
<tr>
<th scope="row">Age: 0-4</th>
<td>0</td>
<td>9.7</td>
</tr>
<tr>
<th scope="row">5-17</th>
<td>23.6</td>
<td>18.0</td>
</tr>
<tr>
<th scope="row">Total 0-17</th>
<td>20.6</td>
<td>16.1</td>
</tr>
the table's id is "datatable". i want to return an array of the contents of each first td and then format it like this:
0,23.6,20.6
i am very new to using arrays...
You can do this:
var l1 = $('#datatable td:nth-child(2)').map(function() {
return $(this).text();
}).get();
//l1 = [0, 23.6, 20.6]
See here for a demo
This uses .map() to get an array from the elements. Your main problem is that :first-child needs to be the first child of the parent, it doesn't mean the "first child of this type", so only a <th> would be :first-child in your code. Instead you need the 2nd child, or :nth-child(2) to get the first <td> element.
td:first-child won't match anything because none of the <td> elements are the first children (they are preceded by <th>). Instead, use td:nth-child(2).
This should work:
var values = [];
$('#datatable tbody tr').each(function () {
values.push($('td:first', this).text());
});
console.log(values);
Explanation:
Line 1: create the values variable and set it to an empty array.
Line 2: loop over every tr in #datatable.
Line 3: add the text of the first td in the tr to the values array.
values is now populated with the values.

Categories

Resources