hengsopheak
hengsopheak

Reputation: 401

How make automatic calculate

How to calculate using jquery or Javascript in Codeigniter as below requirement I have 3 input element to calculate after user complete they form element :

1, Quantity
2, Unitprice
3, Total.

By Total = quantity * unitprice.

<td><?php echo form_input('quantity','',' class="form-control"')?></td>
<td><?php echo form_input('unitprice','',' class="unit form-control" placeholder="unit pricee"')?></td>
<td><?php echo form_label('','total','class="form_control"')?></td>

enter image description here

I try to write javascript like this

<script type="text/javascript">
    $(document).ready(function () {
      $('.unitprice').keyup(function () {
         Calculate();
         });
    });

function Calculate() { 
             var quantity = document.getElementsByClassName("quantity").val();
             var unitprice = document.getElementsByClassName("unitprice").val();
             var total = quantity * unitprice;
              $('.total').val(total);
              } 
    </script>

But it is not work

Thanks advance!!!!

Upvotes: 0

Views: 1808

Answers (2)

jogesh_pi
jogesh_pi

Reputation: 9782

Try like this:

$(function(){
$('.qty, .unit').on('blur', function(e){
  var qty = parseFloat( $('.qty').val() ), 
      unit = parseFloat( $('.unit').val() );

  if( isNaN(qty) || isNaN(unit) ) {
    $('.result').text('');
    return false;
  }

  var total = qty * unit;
  $('.result').text( total );
});
});

DEMO

Upvotes: 1

Sgnl
Sgnl

Reputation: 1960

Here's a basic example, since I was bored. Fiddle - http://jsfiddle.net/sgnl/44ts8ucf/1/

html

<input type="text" id="quantity" class="calc_element"> Quantity
<input type="text" id="unit_price" class="calc_element"> Unit Price
<div id="total"></div>

javascript

// get some IDs or classes on your elements to target them easily
var total = $('#total');

// bind an event that triggers on KEYUP
$('.calc_element').on('keyup', function(){
  // when triggered get the values from the input elements
  // via jQuery's '.val()' method
  var quantity = $('#quantity').val() || 1;
  var unit_price = $('#unit_price').val();

  var result = (quantity * unit_price) + " total";

  // set the innerHTML of the div to your calculated total
  total.html(result);
});

YMMV, thats the jist of it, some tweaking will need to be down for your code.

Upvotes: 1

Related Questions