JQuery Client-Side Calculations
In this article I’ll guide you how to perform client side calculations using JQuery. JQuery is a very powerful tool for client side validations, calculations, animations etc.
You might have come across situations where you need to perform calculations based on one input to several others. One good example would be, assume you are supposed to offer discounts to your online clients. In a situation like this you may need to update both Discount Value and Net value based on the discount percentage and Amount. This can be achieved without going to the server or without using a scripting language like PHP or ASP.NET.
Let’s look at the Jquery Example more closely. It demonstrates a typical scenario we encounter in day to day web programming. Prerequisites are Jquery library as a reference on the top of your page. You can download Jquery library from here.
<script type="text/javascript"> $(document).ready(function() { $("#txtDiscount").change(function() { var dis = $("#txtDiscount");//reading the discount percentage var disamt = $("#txtDisAmt");//reading the discount amount var amt = $("#txtAmount");//Reading Amount var net = $("#txtNetAmt");// Reading Net amount if (amt.val() > 0) { if (dis.val() > 0) { net = (amt.val() * (100 - dis.val()) / 100) + '';//net amount calculation disamt = amt.val() - net;//Discount amount calculation $("#txtNetAmt").attr("value", net); //assign net amount to html control $("#txtDisAmt").attr("value", disamt); //assign Discount amount to html control } else { amt = amt + ''; $("#txtNetAmt").attr("value", amt); } } }); }); </script>
Using Jquery we can trace the change event of the discount percentage as shown above code. Next step is to read the current values into variables for further calculations. Based on valid values you can process the calculations as shown in the above code. The most important thing is with Jquery, you can select the value using ether id or class. once it is captured into a local variable by using the .val() method you can retrieve the real value hold by the html control. The other important thing that you may need to know with Javascript and Jquery if you want to convert number to string you need to concatenate the value with empty string. only string values can be bound to html controls back again.
Lastly you need to rebind the processed values into html controls. This you can perform using the Jquery method arrr(). It accepts two parameters. One is the attribute name and the other attribute value. As you can see in the above code i have used the attr() to bind back the values to html controls.
Happy coding.
2 Comments
Join the discussion and tell us your opinion.
Found this on Yahoo and I’m glad I did. Interesting article.
Hello it is the second time, that I dicover this blog I think became blog friends lol!
Anyway nice post!I´m Diogo I´m new at this web surfing things!
Learned a lot here