Search code examples
jquerydom-traversal

assign unique id to <input> button and read it using jquery


I have a minor problem, basically I have a hidden input button which is loaded with a unique value from a database table: <input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' /> This button gets repeated according to how many rows are returned through this method:

while ($row = $result->fetch()) {
    echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
    echo '<tbody>';
    echo '<tr>';
    echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
    echo '<td width="203"><span class="itemElements itemName">'. $row["Name"] .'</span></td>';
    echo '<td width="203"><input type="submit" class="btnMinus linkbtnType2" value="-"><input type="submit" class="btnPlus linkbtnType2" value="+"></td>';
    echo '<td width="135"><span class="qtyNum">('. $row["Qty"] .')</span> <br />';
    echo '<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />';
    echo '<span class="qtyRemoveLink"><input type="submit" class="btnRemove linkbtn" value="Remove"></td>';                            
    echo '<td width="180"><span class="itemElements orderStatus">In Stock Usually dispatched within 24 hours</span></td>';
    echo '<td width="175" class="itemPriceRow"><span id="itemPrice">€ '. $row["Price"] .'</span></td>';
    echo '</tr>';
    echo '</tbody>';
    echo '</table>';
    echo '<br>';                            
}  

Im using a jQuery method to use read this value from the hidden button however it is only reading the value from the first input button generated. I tried changing the the button from an ID to a class but with no luck.

This is the jQuery method:

$('.btnRemove').click(function() {
    var productId = $(".ProductId").val();
    $.ajax({
        type: "POST",
        url: "functions/deleteCartItem.php",
        data: "productId="+productId+ "",
        success: function(msg){   
            alert(msg);
        }
    })
})

A possible solution I can think of is to add a unique id to each button so they can be identified not only by name but also by id. However this poses a problem in reading it from the jQuery method.

Any ideas?


Solution

  • try :

    var productId = $(this).closest('tr').find(".ProductId").val();
    

    this referring to $('.btnRemove') as DOM element.

    jQuery(this).closest("tr") we are traveling up the DOM tree searching for the first tr element.

    From here we search for .ProductId.

    Andreas