testc calcx

How to calculate form field values both directions?

I found Calcx — great and powerful jQuery plugin for building a calculation form and modified one of it’s examples for my need, but did not figure out is there possible somehow to make it work like i wanted in description above.

There is some additional problems I did NOT found a solution:

  • fields with formulas and set readonly: false should be editable. Fields in my example with class .sum still don’t are editable. Why?
  • I added + and — buttons around qty -field to incr/decr functionality, but to get them work properly I had to detach Calcx functionality and attach then again. Is there simpler way to achieve that?

Disclaimer the solution for my problem may involve other techologies besides Calcx, too. Maybe some plugin or framework has better tools for my needs.

For the history I add code example here too, but to play with it is maybe better to look in the JSfiddle

       .plusminus    
- +
- +
- +

@Sukima: Question: how to make form rows calculate other way too? If i enter SUM i want it to calculate UNIT PRICE. Now it works only other way.

@w.k:I am close to finding another solution tomorrow i’ll try to refine the code and post the answer.

@w.k:haaa, now i understand your question (better late than never), i’m sorry for my post that is wrong. Now i try to improve it.

@w.k:now the script for me is Ok (but i’m going crazy), tomorrow i’ll try to make a new version of the script with a few changes in the html code, thanks for the BIG GAME.

5 Answers 5

I recomended you to use the library ractive.js. Take a look how simple and automatic is it’s two way databinding: http://learn.ractivejs.org/two-way-binding/1/

In this simple way you can use expressions like > and save a lot of code. http://learn.ractivejs.org/expressions/2/

Читайте также:  How do I make a container box in HTML? - example

You can add js functions between > and events:

You can know how to setup ractive in 60 seconds: http://www.ractivejs.org/60-second-setup

And learn it easily in it’s interactive tutorial: http://learn.ractivejs.org/hello-world/1/

I added this jsfiddle as an example.

Seems promising! Could you add some aggregation examples too? Like average price, count of rows, total amount?

Johann — I’ve updated your fiddle to take advantage of ractive.js computed properties (new in 0.4.0) jsfiddle.net/FarWn/7

Total amount mustache is not updating properly. Anyway that computed property is cool. It makes the html to be even cleaner. I think I’ll migrate to 0.4.0 version.

@JohannEchavarria: ooh, neat, +1! I was going to recommend knockoutjs writeable computed observables, but ractive binding looks really intuitive.

I don’t like libraries, especially if I can avoid them. And you can clearly avoid them here.

I basically put all the data of each item in self-made

On every input, and I immediately have the desired row. From there I’m going to find the other values.

$(document).ready(function() < function calcTotal()< var items = $("#itemlist row").length; var sums = $(".sum"); var total = 0 for(var i = 0; i < items; i++)< if(sums.eq(i).val())< total += parseFloat(sums.eq(i).val()); >> $("#total").val(parseFloat(total).toFixed(2)); > function calcSum(object) < var row = $(object).parent(); var qty = row.find(".qty"); var prc = row.find(".prc"); var sum = row.find(".sum"); var disc = row.find(".disc"); var newSum = qty.val()*prc.val()*(1-disc.val()/100); sum.val(parseFloat(newSum).toFixed(2)); calcTotal(); >function calcPrice(object) < var row = $(object).parent(); var qty = row.find(".qty"); var prc = row.find(".prc"); var sum = row.find(".sum"); var disc = row.find(".disc"); var newPrice = -100*sum.val()/(disc.val()-100)/qty.val(); prc.val(parseFloat(newPrice).toFixed(2)); calcTotal(); >$('.plusminus').click(function()< var operator = parseFloat($(this).text()+"1"); var row = $(this).parent(); var qty = row.find(".qty"); var qtyVal = parseFloat(qty.val()); qty.val(parseFloat(qtyVal+operator)); calcSum(this); >); $(".prc, .disc, .qty").blur(function()< calcSum(this); >); $(".sum").blur(function()< calcPrice(this); >); >);  
- + - + - +

Oh, and I revamped the plus-minus thing a bit, sorry.

@w.k

should work perfectly fine as well. It’s just feels more personal when I’m using custom tags, and I can find things more easily in my own code.

XiozZe, I like your idea of dealing with elements through the parent element very much. Still, the ractive.js solution by Johann is more proper for the current task. Thank you!

Читайте также:  Java create stream from list

Seems my question was not clear enough. I post my own solution for my problem. It is using just jQuery and is not so generic as it would be with some additional plugin. But it acts exactly as I want, furthermore I added functionality to have ranged subforms inside the same form. Here is jsFiddle version to play with, and below is solution as a whole.

Now is possible to change row sum so that price is calculated based on it, and vice versa too.

     .plusminus    
- +
- +
- +


- +
- +


- +
- +
- +
- +


I’d like still to see more general and effective solutions here!

You are not likely to find a component for that, because most workflows are optimized for one-way processing: having at least two parameters to define a result. Other directions are ambiguous. Take your example with unit price (UP), quantity (Q) and price (PR) where PR=UP*Q. There is no real «common usecase» to enable PR editing; what would that mean: you need to calculate a new UP=PR/Q or a new Q=PR/UP? (If you can decide it now, that does not mean that there are not tasks where both of the choices, or only the other one is adequate. Having the 3 fields you have a=fn_a(b,c), b=fn_b(a,c) and c=fn_c(a,b) to calculate values. When one of them (say X) is edited, that obsoletes the X=fn_X. calculation, but you still have two others to choose from (and if a real change happened, then generally both will assign different values). The choice between the two formulas might depend on context and/or value entered and/or the order the controls were last used in. This simply is not a question of framework, but an integral part of the page’s unique function. If you have designed how that should work then you may get some aid from a framework. AngularJS allows you to bind every control to a property of an object, and so the object can store the relevant state (e.g. the order in which the controls have been used) and alter its calculation behavior accordingly (e.g. always re-calculate the least recently entered parameter based on all more recent ones).

Читайте также:  Clear all cookie javascript

Did you look @Johann answer? Ractive.js looks very nice for my kind of task. And, yes there are usercases like this. I don’t know how common they are, but for me it seems usual to recalculate unit price based on the sum. Recalculating quantity is never required for me, but I see usercases for that too: little boy comes to candy shop and says he has one dollar, how many candys could he get for it?

Of course I looked. Reactive.js strikes me a bit too simple for the general case. I don’t see how a two-way sync can be implemented; but I don’t really know what’s under the hood in Reactive. I think everyone should decide which answer suits the current task best. My suggestion emphasizes that no matter how complex rules you think of, Angular can help you with that, because in Angular you create an object to govern the behavior, so it can store state, and even react to external events. It surely is the heaviest tool, but a good choice if you already use it or others don’t suffice.

Modifying the html code i’ve create this script jQuery without external plugin.
Fiddle
This script computes tot-row, tot-group, price-per-unit, average-price, and shows the last value changed.
is possible to change row sum and price is recalculated.
Probably due to my ignorance I don’t understand the question of ranges could you please give me some clarification?

  

Источник

How to calculate form fields values to update hidden field value?

Should that happen whenever the user inputs something, or on a button press? And are the input values treated as numbers that should be added up?

Yes, whenever the user inputs something in the above fields, it updates the span and the hidden field

9 Answers 9

This should do what you want to achieve:

function displaySum () < var sum = 0; // iterate over the input fields $('.auto-sum').each(function () < var value = $(this).val() || 0; var number = parseInt(value, 10); // parse the input value to an integer if (isNaN(number)) < number = 0; >sum += number; // add the value to the sum >); // set the value of the two elements $('#amountTotal').text(sum); $('#total').val(sum); > // whenever the value of one of the input fields changes, call the displaySum function $('.auto-sum').on('change, keyup', displaySum);

I tried with blur method for after mouseleave from input and check all input values and added ! Then update to wanted element !!

$("input").on("blur",function() < var total = 0; $("[type='text']").each(function()< if($(this).val() != "") < total += parseInt($(this).val()); >>); $("#amountTotal").text(total); $("#total").val(total); >); 

Try with query each() function .Use with parseFloat convert the string to number .for real time update do with keyup event

$('.auto-sum').keyup(function()< var a=0; $('.auto-sum').each(function()< a+=parseFloat($(this).val()) >) $('#amountTotal').text(a|0) $('#total').val(a|0) console.log($('#total')[0].outerHTML)//its show the hidden field value >)

You can use inputs to force values entered to be a number.

From there you can call jQuery with the query selector input.auto-sum to get all of the input elements with the class auto-sum

Using the each function you can add the numeric to an accumulator to get the total.

You can then use jQuery with the query selectors needed to set any other elements on the page with the Total value.

function getTotal() < var total=0; $('input.auto-sum').each(function(i,e) < total += Number($(e).val()); >); $('#amountTotal').text(total); $('#total').val(total); >
 Score 1:  
Score 2:
Score 3:
TOTAL: 0

Источник

Javascript calculate form values

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью