Pergunta

Eu tenho uma estrutura de tabela HTML que é algo ao longo das linhas de:

PRICE       QUANTITY    TOTAL
[5____]     [2____]     10 (TOTAL1=PRICE1*QUANTITY1)

Os valores na coluna preço e quantidade são editáveis. Estes são os campos do formulário HTML.

Os valores na coluna total não são editáveis. Em vez disso, são funções diretas das colunas à esquerda.

A representação HTML da tabela é:

<table id="some_id">
  <tr>
    <td><input type="text" name="price1" value="5" /></td>
    <td><input type="text" name="quantity1" value="2" /></td>
    <td><input type="readonly" name="total1" /></td>
  </tr>
</table>

Usando jQuery eu gostaria de fazer com que o valor de "Total1" sempre reflete o valor dos tempos "Price1" "quantity1".

Pergunta: Eu entendo que existem inúmeras maneira de conseguir isso - mas o que seria o mais limpo maneira mais concisa para fazê-lo usando jQuery

?

Uma vez que "auto-atualização / campos derivados" deve ser um caso de uso jQuery bastante comum eu diria que existe algum melhor método de prática para alcançar este objectivo.

Foi útil?

Solução

O jQuery Cálculo plug-in ( jquery.calculation.js ) resolve este problema exato.

Os seguintes mostra o código como usar jQuery Cálculo para resolver o problema neste caso em particular:

function recalc() {
  $("[name=total1]").calc(  
    "p * q",
    {   
      q: $("input[name=quantity1]"),
      p: $("input[name=price1]")
    },
    function (s) {
      // set number of decimals of resulting value to zero
      return s.toFixed(0);
    },
    function (t) {
      // this runs after the calculation has been completed
    }
  );
}
$("input[name=price1]").bind("keyup", recalc);
$("input[name=quantity1]").bind("keyup", recalc);
recalc();

Outras dicas

Isso deve fazer o truque:

$('input[name^="price"], input[name^="quantity"').keyup(function() {
    $rowTds = $(this).closest('tr').children('td'); // get the row tds
    price = $rowTds.eq(0).children('input').val(); // get the price
    quantity = $rowTds.eq(1).children('input').val(); // get the quantity
    $rowTds.eq(2).children('input').val(price * quantity); // store the value in the total field
});

Este provavelmente poderia ser encurtado em 2 linhas (dentro da função), mas acho que isso mantém-lo legível.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top