I have DOM like this:
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
<div class="parent">
<button class="add-tr">Add</button>
<table class="child">
<tr data="0"></tr>
<tr data="1"></tr>
...
</table>
</div>
...
When I click on the Add button, I would like to get the value of the data attribute from the last of it own parent class.
I am using this method to get the last element,but it doesn't work.
$('.add-tr').click( function() {
var last = $(this).parent().find('.child:last').attr('data');
alert(last);
})
Any idea why? Or any other suggestion to get the last element in the table?
UPDATE
Yes, I found the problem, turn out is I forgot the 'tr'. Thanks for your guys answer. All your guys giving the correct answer, I wish I can accept all your answers. Thanks
Try this
var last = $(this).parent().find('.child').find('tr').last().attr('data');
In your example you get last table, but you need get last tr
Example
'.child:last' selector will select the last element having child class. As child class is applied to <table>, this selector will select table element, while you want to select last <tr>.
As there is no data attribute on <table>, .attr('data') on it will return undefined.
To get the value of data attribute on last <tr> use the selector tr:last.
var value = $(this) // Button that is clicked
.parent() // Direct parent element i.e. div.parent
.find('.child tr:last') // Get the last <tr> inside .child
.attr('data'); // Get value of data attribute
As the .child element is next to the button, next() can be used to get the table.child element.
var value = $(this) // Button that is clicked
.next('.child') // Next element i.e. table
.find('tr:last') // Get last <tr>
.attr('data'); // Get value of "data" attribute
I'll recommend to use data-* attribute to store data in custom attribute.
<tr data-num="0">Foo</tr>
<tr data-num="1">Bar</tr>
And to get the value of custom data attribute use data()
.data('num')
If you just want to get the index of the last tr, there is no need to store that on element. You can get the index by using the index().
.index()
This will return index of an element. Note that this is zero-based index which is exactly how you want.
$(".parent").click(function(){
$(this + " tr:last-child").attr("data");
});
should do.
Your code was almost correct, you missed tr:last , i.e.:
var last = $(this).parent().find('.child tr:last').attr('data');
DEMO
http://jsfiddle.net/tuga/vr1knxqq/3/
$('.add-tr').click( function(event) {
var last = $(event.target).next().find("tr").last().attr("data");
alert(last);
})
fiddle-example
You can get an array of the tr elements by using find('.child tr')
and to get the last element in that array you can use last().
Putting it all together you have this:
$('.add-tr').click( function() {
var lastTr = $(this).parent().find('.child tr').last(),
lastData = $(lastTr).attr('data');
alert(lastData);
});
I have setup a codepen here http://codepen.io/anon/pen/aOzmKg to show this working.
Related
I want to get attribute value (data-resource-id) in tag. But this tag don't have id or class. I just need inside show alert when clicked. This is my code:
<table>
<tbody>
<div class="x">
<tr data-resource-id="first"> //will show alert "first" when clicked
<tr data-resource-input="second">//show nothing when clicked
</div>
<div class="y">
<tr data-resource-id="first"> //show nothing when clicked
</div>
this is my javascript code:
$('.x').on('click','????',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})
I don't know what code to write in '????'. What code should i write?
This updated version of your code might work for you
$(document).on('click', '.x [data-resource-id]', function() {
const resourceId = $(this).attr('data-resource-id');
alert(resourceId);
})
Note, your original code had a variable named resource-id — but hyphens are illegal in javascript identifiers. So you must correct that variable name to resourceId instead
'????' became '.x [data-resource-id]' so that clicks to anything matching that selector are handled
var became const for good measure
Corrected tab consistency
Get all the tags that have your attribute and value:
'tr[data-resource-id="first"]'
Get just the first tag that matches your attribute and value:
'tr[data-resource-id="first"]:first'
You can use data attribute as selector. As below
$('.x').on('click','tr[data-resource-id="first"]:first',function(){
var resourceid = $(this).attr('data-resource-id');
alert(resourceid);
})
I have a table of elements like this:
<tr id="elementId">
<img name="img" src=""/><br/>
<input name="text" type="text"/><br/>
<input name="button" type="button"/><br/>
</tr>
Each element is exactly the same, except of its id.
I try to update the elements with javascript, but I have no clue how to get the child nodes by their name.
My code:
//get element
var element = list.rows[i];
//update nodes
element.getElementByName("img")[0].src = someImg;
element.getElementByName("text")[0].value = someText;
element.getElementByName("button")[0].value = someOtherText;
The code doesn't work, because element has no function getElementByName.
Is there any other way to get the nodes by their name?
element.querySelector('[name="thename"]') or element.querySelectorAll('[name=2thename"]')
The function is getElementsByName. Elements is plural.
Note that it returns an array-like HTML Collection, so you'll need to grab the first item off it too (with [0]).
Additionally, you might find that your elements aren't actually in your table row as you are missing table cells. Validate your markup: http://validator.w3.org/nu/
In order to select all alements with a tagname in the whole document you may use
listElements = document.getElementsByTagName();
Inside a certain element, you may use
selectedElement = element.getElementsByTagName();
Notice this functions returns an array with the elements selected. If there is only one element, it will be in
listElements[0]
in the first case, or
selectedElement[0]
in the second.
I am trying to select array of "tr" based on "td" class, once I got the array I want to get array of all tr's custom "data-fid" value.
This what I got,
var rows = $("#tableB tr").children(".New.selected") // returns td, but I want tr
Once I got rows, I want to get array of there data-fid values,
var selectedValues = rows.attr('data-fid'); // not sure if it will work but i guess this is how i would do it
I am trying to google but my luck with finding right wording is just failing badly todya.
<table id="tableB" class="dmctable2">
<tr data-fid="1" Class="selected"><td></td><td></td><td class="New selected"></td></tr>
<tr data-fid="2"></tr>
<tr data-fid="3" Class="selected"></tr>
</table>
you can use :has() selector for that.
Selects elements which contain at least one element that matches the specified selector.
Like this:
$("#tableB tr:has(.New.selected)")
and to get the data values in array:
$("#tableB tr:has(.New.selected)").map(function(){return $(this).data("fid");}).get();
An other alternative which is faster would be to select the .New.selected element and then access to its parent:
$("#tableB tr .New.selected").parent('tr')
<table>
<tr>
<td>me</td>
<td>you</td>
<td>we</td>
</tr>
</table>
Using Jquery i want to know which childrin was clicked and get the number of this childrin. like, if I click you, i want to get 2 and if we, then 3.. if me, then 1.
is there something like .nthchild(); in Jquery?
here is my fiddle to test: http://jsfiddle.net/vfp9x/
Simply use $(this).index(), you also have wrong id for table in live demo, it should be table1
Remember the index is zero based so you will get zero 0 for first element and 1 for second element and so on.
Live Demo
$('#table1').on('click', 'td', function () {
$('#out').text($(this).index()+1);
});
.index()
If no argument is passed to the .index() method, the return value is
an integer indicating the position of the first element within the
jQuery object relative to its sibling elements.
Try,
$('#table1').on('click','td',function(){
var child_number = $(this).closest('tr').find('td').index(this);
$('#out').text(child_number);
});
DEMO
Simply use .index() as per the other answer provider suggested, and also keep this way of getting the index also. it would helpful for you in some other contexts, like getting the index of the current element from a collection of elements (not siblings to each other)
Try Like
$("#ul").on('click', 'td', function () {
debugger;
alert(this.id);
});
Demo
I want to reload a particular div, which has an id corresponding to a table element's id... (the div has only one table child).
the alert says tID is undefined.
javascript:
function (msg) {
var tID = $("table", msg).attr('id');
alert(tID);
$("#reloadme_"+tID).html(msg);
}
html:
<div id="reloadme_2036">
<table id="2036" class="customCSSclass">
...table contents...
</table>
</div>
Where have I gone wrong?
find looks for descendants of the current set of elements inside the jQuery object, you should use .filter which filters the elements in the jQuery object itself:
$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it
Of course, if it is the only element inside the jQuery object, there is no need for filtering. =]
Also, you'd use .find for e.g. looking for tr/tds (or any other element(s)) that are descendant of the table element referenced inside of your jQuery object.
Maybe this is what you're looking for?
function reload(msg) {
var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
alert(tID); //alerts 2036
$("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');
If so, what you are likely looking for is javascript's .match() method which will find the id number within a string.
Check out the JSFiddle.
You have to try like this
var msg='<table id="2036" class="customCSSclass"></table>';
alert($(msg).attr("id"));