onbids
onbids

Reputation: 53

value won't display by each row

I have a problem.
an array would return me some dynamically data from it.

<?php 
foreach($ItemArray as $key => $value) {
    echo '
    <tr><td height="30" valign="middle">'.$value['nr'].'</td>
    <td valign="middle">'.$value['product'].'</td>
    <td valign="middle">'.$value['describe'].'</td>
    <td valign="middle" id="price_'.$key.'">'.$value['price'].'</td>
    <td valign="middle" class="box_darker" id="amount_'.$key.'">
    <input name="Field_Amount_'.$key.'" id="Field_Amount_'.$key.'" class="Field_Amount" type="text" /></td>
    <td valign="middle" id="price_'.$key.'">$key</td></tr>'; }
;?>  

Now I would test if the value returns me the right one when click on belong field (td/price)

$(document).on('click', '[id^=price_]', function(){
var Amount = $('[id^=Field_Amount_]').val();
alert(Amount);
});  

But nevermind wich field (td/price) in each row I click, it alert me only the value from first row! maybe because the data loads dynamically?

Sorry for that poor English.

Upvotes: 0

Views: 68

Answers (3)

gururaj
gururaj

Reputation: 11

Try This

$(document).on('click', '[id^=price_]', function(){
    var key = $(this).attr('id').split('price_');
    var amount = $("#Field_Amount_"+key[1]).val();
});

Upvotes: 1

Friederike
Friederike

Reputation: 1282

Your trigger event is working fine since every row reacts to the click.

What's "wrong" is the selector for the Field_amount. This always selects the first Field_Amount_ because the selector is working on the whole page.

Try using the .closest() function:

$(document).on('click', '[id^=price_]', function(){
    var Amount = $(this).closest('[id^=Field_Amount_]').val();
    alert(Amount);
});

Upvotes: 2

h2ooooooo
h2ooooooo

Reputation: 39532

That's because you perform your second search on the global scope as well, and val() will return the value from the first element. Use $(this).parent().find() instead:

$(document).on('click', '[id^=price_]', function(){
    var Amount = $(this).parent().find('[id^=Field_Amount_]').val();
    alert(Amount);
});  

Alternately, you should also be able to use .closest():

$(document).on('click', '[id^=price_]', function(){
    var Amount = $(this).closest('[id^=Field_Amount_]').val();
    alert(Amount);
}); 

Upvotes: 5

Related Questions