2010-01-30 10 views
7

Sto facendo una libreria e voglio aggiungere un modulo di ordine jQuery di fantasia. Il punto è che l'utente deve scegliere la quantità di un libro con un segno meno e più e quindi lasciare che JavaScript calcoli una somma totale per quel libro.Trova campi di immissione nella riga della tabella corrente con la classe

Ho un markup come segue:

<tr> 
    <td><p>Book title</p></td> 
    <td><p><a href="#" class="bookDecrement">-</a><input type="text" class="bookQuantity disabled" disabled /><a href="#" class="bookIncrement">+</a></p></td> 
    <td><p><input type="text" class="bookPrice disabled" value="70" disabled /></p></td> 
    <td><p>=</p></td> 
    <td><p><input type="text" class="bookTotal disabled" disabled /></p></td> 
    </tr> 

Come faccio a raggiungere la classe bookPrice e bookTotal in questa riga con jQuery? Dato che ho più titoli di libri, devo solo accedere all'input archiviato nella riga corrente.

Grazie!

risposta

23

Questo dovrebbe farlo:

$('.bookDecrement, .bookIncrement').click(function() { 

    // Get the current row 
    var row = $(this).closest('tr'); 

    // Determine if we're adding or removing 
    var increment = $(this).hasClass('bookDecrement') ? -1 : 1; 

    // Get the current quantity 
    var quantity = parseInt(row.find('.bookQuantity').val(), 10); 
    // Adjust the quantity 
    quantity += increment; 
    // Quantity must be at least 0 
    quantity = quantity < 0 ? 0 : quantity; 

    // Get the price 
    var price = parseFloat(row.find('.bookPrice').val()); 

    // Adjust the total 
    row.find('.bookTotal').val(quantity * price); 

    // Return false to prevent the link from redirecting to '#' 
    return false; 
}); 
+0

Oh grazie mille! Non ho davvero bisogno che tu scriva tutto per me, ma non mi dispiace :)! Grazie ancora una volta –

13

si può arrivare a un antenato del tr e si scende di nuovo per l'ingresso all'interno. Così:

$("a.bookIncrement").click(function() { 
    $(this).closest("tr").find("input.bookPrice").doSomething(); 
}); 
+0

Bello! Grazie! –

Problemi correlati