Reputation: 608
I am curious to what would be a good practice in getting the closest selected option (value) next to a button. I have came up with two different ways but not sure which one is better.
var find1 = $(this).closest('td').find(':selected').val();
var find2 = $(this).closest('td').children().eq(0).val();
I have created a jfiddle to help http://jsfiddle.net/9kxces0n/3/
If you are curious why I use:
$(document).on('click', '.get-col3-value', function(){});
It is because I am creating rows using an "add row" button and need to be able to register the event. If I did a simple
$(".get-col3-value").click(function(){});
It wouldn't register the click event when creating a row in the table.
Upvotes: 2
Views: 929
Reputation: 178275
Since they are adjacent, I suggest .prev()
Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.
var find3 = $(this).prev().val();
Also you can give the table an ID and do
$("#tableid").on("click",".get-col3-value",function() ...
to shorten the path to the input
Plain JS:
function getPreviousSibling(obj) {
var sib=obj.previousSibling;
while (sib.nodeType!=1) sib=sib.previousSibling;
return sib;
}
window.onload=function() {
var classname = document.getElementsByClassName("get-col3-value");
var myObj = function(){
console.log(getPreviousSibling(this).value)
}
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('click', myObj,false);
}
}
Upvotes: 2
Reputation: 328
See that question, it resolves many doubts about how to point to exact element without "heavy memory" practices jQuery pitfalls to avoid
As they say I suggest you to make use of id as much as possible and no to use the .find() or the classes as a context..
in your code if you are not able to restrict by id on the select option try to restrict the context as much as possible, putting an id on the table for example.
Edit suggested by mplungjan comment
Edit (again...sorry)
How could it be the solution (proposed by @mplungjan) in pure javascript...I make a try but could'nt reach the prevSibling node... see it here. I think you have go up to the parent and then iterate across the childnodes
var classname = document.getElementsByClassName("get-col3-value");
var myObj = function(){
console.log(this.previousSibling.tagName)
}
for(var i=0;i<classname.length;i++){
classname[i].addEventListener('click', myObj,false);
}
http://jsfiddle.net/81hk9gw3/44/
Upvotes: 0
Reputation: 2869
It looks like .siblings() method works too, and I guess it's alright to use it because there's only sibling.
var find2 = $(this).siblings().val();
Upvotes: 0