Recently developed a project, you need to implement the user in the Web form in a number of input boxes, immediately automatically calculate the sum of the sum of the total number of inputs, and displayed in the specified input box, the function of the implementation of the principle is simple, It is only necessary to calculate the sum in the onchange event of input and assign the result to the specified input box, the code is as follows:
$ ("Input.syxcost"). Change (function() {computereceivedsyxcost ();}functionComputereceivedsyxcost () {//Calculate plus Total varSyxcost=0; $("Input.syxcost"). each (function(){ varCost=parsefloat ($ ( This). Val ()); if(!IsNaN (cost)) Syxcost=syxcost +Cost ; }); $("#receivedsyxcost"). Val (syxcost);//Show Final Results}
Originally thought this solved, in Google Browser is really ok, but in IE 9, but found in input number, and will not immediately trigger the change event, there are compatibility problems, search on the internet a lot, also said there is this problem, there is no way, I only have to rely on the implementation of the situation to write, My idea is that when input gets the focus, it gets the current value and stores it in the custom property of that input (for example: Data-oval), and then when input loses focus, gets the current value in the same way as the values in the previously existing custom property, if not the same , the value is changed, it needs to be recalculated, otherwise ignored, the implementation code is as follows:
$ ("Input.syxcost"). Focus (function(){ $( This). attr ("Data-oval", $ ( This). Val ());//to save the current value in a custom property}). blur (function(){ varOldval= ($ ( This). attr ("Data-oval"));//get the original value varNewval= ($ ( This). Val ());//Get Current value if(oldval!=newval) {computereceivedsyxcost ();//not the same is calculated } });
After repeated verification, in all browsers are displayed normal, solve the problem of compatibility!
Original from my personal website: http://www.zuowenjun.cn/post/2014/09/22/39.html
Questions about resolving jquery's incompatibility with the INPUT element change event