I have 3 textboxes, 1st for Quantity, 2nd for Price and 3rd for Total Price.
<div class="form-group">
@Html.LabelFor(model => model.quantity, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.quantity, new { htmlAttributes = new { @class = "form-control", @type = "number" } })
@Html.ValidationMessageFor(model => model.quantity, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.price, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.price, new { htmlAttributes = new { @class = "form-control", @type = "number" } })
@Html.ValidationMessageFor(model => model.price, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.totalprice, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.totalprice, new { htmlAttributes = new { @class = "form-control", @type = "number" } })
@Html.ValidationMessageFor(model => model.totalprice, "", new { @class = "text-danger" })
</div>
and here is the controller:
[HttpPost]
public ActionResult Add(Model model)
{
obj.Quantity = model.quantity;
obj.Price = model.price;
obj.TotalPrice = model.totalprice
db.Details.Add(obj);
db.SaveChanges();
return RedirectToAction("");
}
now I want to multiply values of 1st and 2nd textboxes and show them in 3rd textbox. For example if users enter 5 in 1st textbox and 100 in 2nd textbox then it automatically shows 500 in 3rd textbox and if users changes value of 1st or 2nd textbox then value of 3rd textbox should also change accordingly. Thanks.
The first thing you have got to change is the line with the multiplication. It should be: var myResult = myBox1 * myBox2; You should not use innerHTML with input fields - use value. Additional to that, the onchange event fires only when the input looses the focus.
You can listen to the keyup
event of the textboxes in javascript, read the value and do the multiplication and set the resulting value to the third textbox.
Assuming your have jQuery library included in your page.
$(function(){
$("#quantity,#price").keyup(function(e){
var q=$("#quantity").val();
var p=$("#price").val();
var result="";
if(q!=="" && p!=="" && $.isNumeric(q) && $.isNumeric(p))
{
result = parseFloat(q)*parseFloat(p);
}
$("#totalPrice").val(result);
});
});
Here is a working jsbin sample.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With