Dhara Vihol
Dhara Vihol

Reputation: 612

insert the value automatically in input text when another value is given to another input text

In form, I want to insert the value of amount(text input) when value of rate(another text input) . The value which will be inserted in amount is the multiplication of rate and quantity. The value of quantity is taken from database. Here, the value of rate will be inserted by user. After insertion of amount, the value can not be changed. How can i do this?

I have tried below code but result is showing zero every time:

View

<div class="form-group">
  <label for="exampleInputPassword1">Rate</label>
  <input type="text" class="form-control" name="rate" placeholder="Rate" required>
</div>
<div class="form-group">
  <label>Quantity</label>
  <input type="text" class="form-control" name="quantity" placeholder="quantity" value="<?php echo $object['sheet'];  ?> " required readonly>
</div>
<div class="form-group">
  <label for="exampleInputPassword2">Amount</label>
  <?php
  $sheet = $object['sheet'];
  $rate = $this->input->post('rate');
  $amount = $sheet*$rate;
  echo $amount;
  }
  ?>
  <input type="text" class="form-control" name="amount" value="<?php echo $amount;?>" placeholder="Amount" required>
</div>

Upvotes: 0

Views: 1375

Answers (2)

Ravi Roshan
Ravi Roshan

Reputation: 570

Use Javascript for calculation.

I modified your code for your requirement. Your just need to set rate value dynamically from database. Here is your code :

<div class="form-group">
  <label for="exampleInputPassword1">Rate</label>
  <input type="text" class="form-control" name="rate" placeholder="Enter Rate" id="rate" required>
</div>
<div class="form-group">
  <label>Quantity</label>
  <input type="text" class="form-control" name="quantity" placeholder="quantity" value="2" id="qnty" required readonly>
</div>
<div class="form-group">
  <label for="exampleInputPassword2">Amount</label>
  <input type="text" class="form-control" name="amount" value="" id="amt" placeholder="Amount" required>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"   integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk="   crossorigin="anonymous"></script>
<script>
  $('#rate').keyup(function(){
    var rate = parseInt($('#rate').val());
    var qnty = parseInt($('#qnty').val());
    var amt = parseInt(rate*qnty);
    if(isNaN(amt)){
      $('#amt').val('Enter valid rate');
    } else {
      $('#amt').val(amt);
    }

  });

</script>

Upvotes: 0

Martijn
Martijn

Reputation: 514

You can use jQuery to do that:

$(document).ready(function() {
$('input[name="rate"]').on('change',function() {
   var amount = $(this).val()*$('input[name="quantity"]').val();
   $('input[name="amount"]').val(amount);
})
});

Don't forget to include the jQuery api. Also, don't forget to validate the amount after the form is submitted, as users can easily manipulate the value of the input.

Upvotes: 1

Related Questions