How to select a tr element in the middle of "N tr’s" in jQuery?

Asked

Viewed 397 times

2

It has a mounted table, which each row of it is added dynamically. So, inside the <tbody> is added the <tr's> (lines).

Inside the three, there’s the <td's> and each <td> has a input within.

Imagine that I can added 5 t’s. So if I want to catch a value from the first tr, i use:

$('#d_sfiSRV003 #d_GRD_CENTROS_CUSTO tr:first-child').find('input#f_VLR_APROP_CCUST').val();

d_sfiSRV003 - id da pagina;
d_GRD_CENTROS_CUSTO - id da tabela
tr:first-child - seleciono o primeiro tr q tiver
input#f_VLR_APROP_CCUST - busco o input com a id referida e pego seu valor.

But if the tr’s are placed dynamically, as I do to take for example 6 tr’s placed, take the value of input#f_VLR_APROP_CCUST of the 4th tr or any one I choose?

  • All your inputs will have the same ID?

  • first-child don’t take the first, take the first child.

3 answers

1

Do not use ids to capture elements dynamically added (not even to existing ones). A id should be unique on the page.

Alter the id f_VLR_APROP_CCUST for class: class="f_VLR_APROP_CCUST".

Next you will be able to catch the value of input with the selector:

$('#d_sfiSRV003 #d_GRD_CENTROS_CUSTO tr:nth-child(numero_da_linha)')
.find('.f_VLR_APROP_CCUST').val()

Where numero_da_linha is the line number you want to find the input.

0

To catch the elements without knowing their ids you can do as follows:

Catch 3 tr:

$('tr:nth-child(3)')

Catch tr with name:

$('tr[name="nome1"]'`)

In case you wanted to know how many trs you have this way:

var count = $('#id_objeto tr').length

I hope it helps you!

0

With a simple loop, you can work with all the kids of an html tag at once:

$("tr").each(function(){
    ... código ...
})

Entered the loop you can work with the objects however you want

Search on the function each of jquery, it is very powerful

Browser other questions tagged

You are not signed in. Login or sign up in order to post.