Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Find (the index of) a row with a specific data attribute value

I am trying to append a string, myoutput, right after a specific row in a table similar to this one:

<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>

So let's say I want to append my output string after the tr with data-my_other_id='2' (note that in my code, my_other_id = 2 already )

I am trying to accomplish it doing this:

var want = $("tr").find("[data-my_other_id='" + my_other_id + "']").index();

after finding the index, I want to append my output strhing to this row...

$(want).insertAfter(...?);

Also... I noticed whenever I do

alert( want = $("tr").find("[data-my_other_id='" + my_other_id + "']").length)

I get 0 ...

Help please and let me know if my question is not clear enough so I can explain better.

like image 239
murielg Avatar asked Jan 04 '13 23:01

murielg


People also ask

How to find element by data attribute value jQuery?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How do you check if data attribute exists in jQuery?

The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .

Which of the following is correct about the $( this in jQuery?

Which is the correct jQuery selector to select current HTML element? Explanation: The $(this) selector is used to select current HTML elements.


2 Answers

I'm assuming you want to update the content rather than append, but it doesn't really change anything. I don't think you want to use find() that way. Try something like:

var $row = $('tr[data-my_other_id="' + id + '"]');
// should be the index of the tr in the <table>
// this may not be a good idea though - what if you add a header row later?
var index = row.index() + 1; // if you want 1-based indices
$row.find("td").text("I am row #" + index);
like image 71
john_omalley Avatar answered Oct 16 '22 16:10

john_omalley


This is because find will no search siblings, only children. Try attaching your search to table.

html:

<table>
<tr data-my_id='1'> <td> content </td> </tr>
<tr data-my_id='2' data-my_other_id='1' > <td> content </td> </tr>
<tr data-my_id='3' data-my_other_id='2' > <td> content </td> </tr>
</table>​

js:

var my_other_id = 2;
alert( $("table").find("[data-my_other_id='" + my_other_id + "']").length);​

demo: http://jsfiddle.net/gDb3A/

like image 37
Travis J Avatar answered Oct 16 '22 17:10

Travis J