How can I get nth table column value in Javascript - javascript

How can I get nth table column value? Ie. I would like to get 2nd column value.
The first one I get in this way - it works fine, but the nth(2) does not work:
$('body').on('click', '.confirmation1', function(e) {
e.preventDefault();
var produktNazwa = $(this).parents("tr").find("td").first().html();
var produktWaga = $(this).parents("tr").find("td").nth(2).html();
console.log(produktNazwa, produktWaga);
});
Any hints on this please? Thanks.

There is no .nth() in jQuery. Instead you can try with .eq():
Reduce the set of matched elements to the one at the specified index.
var produktWaga = $(this).parents("tr").find("td").eq(2).html();
OR: You can include :eq() as part of the selector:
var produktWaga = $(this).parents("tr").find("td:eq(2)").html();

I don't recall having nth function in jQuery. I might be mistaken, but not that I know of. What you probably want is eq()
var produktWaga = $(this).parents("tr").find("td").eq(2).html();

Related

What is the jQuery syntax to use when trying to get the number of rows in an HTML table where the table selector is a variable

I need to get the number of rows in a table using a variable as the table selector. I get the table with this:
var table_element = $(this).prev('table.w2bw2c-with-artists-table');
I tried this from a previous post but got an error that length was undefined.
var new_with_artist_index = $(table_element).rows.length;
I have seen these methods used to find the number of rows in a table:
var rowCount = $("#tblEmployee td").closest("tr").length;
var rowCount = $('#myTable tbody tr').length;
How can I use one of these methods where the table selector is a variable instead of an ID? Or is there a better way?
You can just use .find() method on jQuery object.
var rowCount = table_element.find('tbody tr').length;
Or, You could get the native table using [] or .get() then use .rows property
var rowCount = table_element[0].rows.length;
var row = $("#tblEmployee td").find("tr");
var rowCount = row.length;
Many ways to do this:
1. jQuery find method
$(tableElement).find('tr').length
2. jQuery context parameter (i call it that way)
$('tr', tableElement).length
3. Plain Javascript
tableElement.querySelectorAll('tr').length
As you see the shortest would be the second variant, i think its also very clear, so if you can utilize jQuery, go for that variant. If you dont have jQuery in your library yet you should probably use the third variant.
querySelectorAll is defined for all DOM Elements and returns a NodeList. There is also a querySelector function, that will return the first match of the selector (so a single Element or null if nothing matches).
NodeList does not extend Array, so if you want to iterate the list, you need to do it that way:
[].forEach.call(tableElement.querySelectorAll('tr'), function(element) {
doSomething();
});
I found an answer from Ricky G at
jQuery: count number of rows in a table
Here's my code:
//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
return $('tr', $(this).find('tbody')).length;
};
To use:
var table_element = $(this).prev('table.w2bw2c-with-artists-table');
var new_with_artist_index = $(table_element).rowCount();
Thanks and a tip of the hat to Ricky G!

Detect if a div with id including number is clicked

My html code has X elements, with their ids in this form:
viewer_mX
Here, X is a number from 1 to m (m can be different each time).
I want to use javascript to get the number X of the respective element when somebody clicks one of these elements.
I realise I should probably use a class (.viewer) and and id (#x) containing the number. However, I am using a library to generate the html elements and I am stuck with this protocol and will have to make the best of it.
This is the javascript I have so far:
$(document).ready(function () {
$("#viewer>...").click(function () {
x = ...
var number = x;
});
});
What's missing in this code (indicated by 3 dots) is that viewer is not the full ID, but could be post-pended with something. I want to store whatever is after the clicked div in number, but I can't figure out which function to use for that.
Try this,
$("[id^='viewer_']").click(function () {
var number = this.id.match(/\d+$/)[0];
});
Why not use class to identify elements and then data-attribute for storing your id (data-id for example) and then get value of this data-attribute?
Otherwise I would personally use something like this
$(this).attr('id').substr("viewer_m".length);
Either split or a reg exp
var id = this.id.split("_m")[1]
or
var id = this.id.match(/\d+$/)[0];
or better yet, use a data attribute
<div data-mid="123">
and reference it
$("[data-mid]").on("click", function () {
var id = $(this).data("mid");
});
A better approach to this, as #Wax Cage mentioned, is to use classes and data attributes for better organizing. Example:
<div class="viewer" data-viewer-id="1">...</div>
$('.viewer').on('click', function() {
var viewerId = $(this).data('viewerId');
// ...
});

How do I access the original element from the jQuery wrapper

Assuming I have this:
var wrap = $("#someId");
I need to access the original object that I would get by
var orig = document.getElementById("someId");
But I don't want to do a document.getElementById.
Is there something I can use on wrap to get it? something like:
var orig = wrap.original();
I searched high and low but I didn't find anything; or maybe I'm not looking for the right thing.
The function for this is get. You can pass an index to get to access the element at that index, so wrap.get(0) gets the first element (note that the index is 0-based, like an array). You can also use a negative index, so wrap.get(-2) gets the last-but-one element in the selection.
wrap.get(0); // get the first element
wrap.get(1); // get the second element
wrap.get(6); // get the seventh element
wrap.get(-1); // get the last element
wrap.get(-4); // get the element four from the end
You can also use array-like syntax to access elements, e.g. wrap[0]. However, you can only use positive indexes for this.
wrap[0]; // get the first element
wrap[1]; // get the second element
wrap[6]; // get the seventh element
$("#someId") will return a jQuery object, so to get at the actual HTML element you can do:
wrap[0] or wrap.get(0).
You can use get() to retrieve the HTML element.
var orig = wrap.get(0);
However, if wrap consists of multiple elements, you will need to know the correct index which to use when you use the get() function.
You can just use var orig = wrap[0]; as far as I know, if there's more than one element. If there's just the one, you can just use wrap without $() around it.
You can use wrap still.. Wrap is the same as 'orig' would be in the above! :)
If you really want:
var orig = wrap;

HTMLInputElement has no method 'val'

I'm looping through cells in a table row. each cell has a text box in it, and I want to take the value of the text box and push it onto an array.
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $(this).children('input')[0].val();
submitvals.push(val);
});
}
Theres more to the function, but this is all that is relevant. For some reason, when I run this code, I get "HTMLInputElement has no method 'val'." I thought that input elements were supposed to have a val() method in jQuery that got the value so this makes no sense. Am I missing something, or doing it wrong?
val() is a jQuery method. .value is the DOM Element's property. Use [0].value or .eq(0).val()....
.val() is a jQuery function, not a javascript function. Therefore, change:
var val = $(this).children('input')[0].val()
To:
var val = $(this).children('input:eq(0)').val()
function dothing() {
var tds = $('#'+selected+' td');
var submitvals = new Array();
tds.each(function(i) {
var val = $($(this).children('input')[0]).val();
submitvals.push(val);
});
}
.val() is a jquery method. Using [0] returns the DOM element, not the jquery element
var val = $(this).children('input:first').val();
What I don't understand, is why none of the suggested syntaxes on this or other questions similar to this seem to work for me. I had to do trial and error and eventually had to use:
MySelectElement.value = x;
It also didn't help that the Visual Studio Intellisense suggestions offer a whole other range of unworking method names, such as ValueOf().

How do I get the id of the selected node in jsTree?

How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected function returns an array of selected list items. If you do .attr on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused() if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');
In jstree version 3.1.1, you can get it directly from get_selected:
$("#<your tree container's id>").jstree("get_selected")
In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
In my case, the data call doesnt work.
I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");
to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
Just use
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
where #FaqTreeView is the id of your div that contains the jstree.
In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing.
What did the trick for me is:
$("#tree").jstree("get_selected").toString();
These are all old answers for old versions. As of version 3.3.3 this will work to get all attributes of the selected node.
$('#jstree').jstree().get_selected(true)[0]
If you then want the id then add .id at the end. You can look at all the other attributes in web developer tools if you copy the above code.
You can use the following code
var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array
With the latest version of jsTree, you can do it as follows:
var checked_ids = [];
$('#your-tree-id').jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));

Categories

Resources