Jquery mobile value overrides toFixed method - javascript

Please check:
http://jsfiddle.net/LdWHH/
Obviously it does not make sense to set it to toFixed(1) first and then to toFixed(2). The point is that the .slider("refresh") seems to have its own internal conversion and thus it ignores or overrides the toFixed method. I don't know.
In my german browser it also displays the . correctly as ,
How can I adjust this manually?
$("#plus3").on("mousedown taphold", function () {
var sv4 = $('#slider-vertical4').val();
var sv4fixed = Number(sv4).toFixed(1);
var total = (Number(sv4fixed) + 0.1).toFixed(2);
$('#slider-vertical4').val(total).slider("refresh");
});

I don't really understand what you're trying to achieve.
If your problem is that using +/- : 5.0 will appear as 5.
You can try doing it in two times, set&refresh then set
$('#slider-vertical4').val(total.toFixed(1)).slider("refresh")
$('#slider-vertical4').val(total.toFixed(1));

Related

Round every textbox to 2 decimal places

This is probably really simple, but for the life of me I can't work out how to do it. So here goes: I have a large form with lots of text boxes, which are all currency based and so need to be rounded off to 2 decimal places. The values of these textboxes are all generated dynamically by some JavaScript functions I wrote, and I can use .toFixed(2); to round them up/down to 2 decimal places. However, it gets tiring and repetitive to have to put this after working out each value of each textbox. How could I write a simple piece of JavaScript (can be jQuery) to target all the textboxes and round them ALL to 2 decimal places?
Thanks for any help :)
P.S Sorry for the lack of any code, but there isn't really any to show, as its all locked up in big functions. But here's what I'm essentially doing:
function workOutSomeVal() {
// lots of code to work out values and stuff
var finalValue = some mathematical equation to work out value;
var anotherValue = a different value;
$(".some-textbox").val((finalValue).toFixed(2));
$(".another-textbox").val((anotherValue).toFixed(2));
} // my question is, how could I get rid of .toFixed(2) and put in a generic statement somewhere to target all the textboxes?
You can have a function you call that does this:
function roundTextBoxes() {
$("input[type=text]").val(function() {
return (+this.value).toFixed(2);
});
}
...and then call that any time any of them changes. Live Example: http://jsbin.com/toyoc/1
It will probably mean that sometimes, a user looking at the page who does the mental arithmetic will find that it doesn't quite add up...
You can give a common class to all the textboxes which you want to be "roundable", and then select then using that class and apply your rounding logic to each of them.
// let's say all the roundable textboxes have the class "roundable"
$('.roundable').each(function() {
var value = // some mathematical equation to work out value
$(this).val((value).toFixed(2));
});
Another appoach:
Why don't you put value.toFixed(2) at the end of your calculation ?
var finalValue = function(){
// var value = some calculation
return value.toFixed();
}
Or - if you need the full value elsewhere, create a new function:
var finalValueView = function(){
finalValue().toFixed(2);
}
function workOutSomeVal() {
// ...
$(".some-textbox").val(finalValueView);
}
Use Math.round(num * 100) / 100

Javascript removing decimals in knockout binding

I've seen there are quite a few questions about decimal precision and display in Javascript. the thing is that I came to a solution that I thought it was gonna be enough for me'
The key thing is that I'm trying to parse to a string to round and then back to numbers using expressions like this.
return parseFloat(num.toFixed(2));
But there are some cases that it doesn't work as expected. To be honest I'm not sure if it has to do with the way I'm using ko or the javascript code for parsing I put in place. But let's say that in the below fiddle you type 14.385 in the upper text box, both fields will be properly rounded and will display the correct number of decimals, but without deleting the number you add 3333 (that means 14.393333) and the upper one won't be rounded. That's just an example because there are some strange behaviours.
Yo can see the fiddle here http://jsfiddle.net/RTexF/
Thanks
Edit. I add the code as per judgeja indication (I didn't understand the reason to ask for a code when you link fiddle, I see the point now)
The script
var decimalValue = 0.25;
function ViewModel() {
var self = this;
self.submittedValue = ko.observable(decimalValue);
self.percentage = ko.computed({
read: function() {
alert('read');
if (isNaN(parseFloat(self.submittedValue())))
return '';
var num = self.submittedValue() * 100;
return parseFloat(num.toFixed(2));
},
write: function(value) {
alert('write');
value = isNaN(value) ? '' : parseFloat((value / 100).toFixed(4));
self.submittedValue(value);
},
owner: self
});
}
ko.applyBindings(new ViewModel());
And the html
<p><input data-bind="value:percentage"></input></p>
<p><input data-bind="value:submittedValue"></input></p>
EDIT:
Know that it's an old one but I wanted to note that adding this to the write method
self.percentage.notifySubscribers(value);
it fixes the issue (ideally we could check against the current value and just notifiy if it actually changes)
Fiddle : http://jsfiddle.net/RTexF/1/ and http://jsfiddle.net/RTexF/2/
It may help you to think about this if you put an alert("read") in the read: and an alert("write") in the write: and then run your example again.
When you change the top box the first time the bottom box is written to through the write and then the top box is re-computed as the submittedValue observable has changed and you'll see the read for percentage being hit.
Next time you edit the top box the write will be hit again as we're changing the value, which makes sense, but since the submittedValue isn't changed, then the read won't happen again as the observable it depends upon won't have changed.

Javascript prototype function: decimal time value to a time string

On a project I'm currently working on in JavaScript, I'm using decimal formats so it's easier to calculate with rather than using an hour/minute format in strings (calendar related project). To display the time on the user's screen though, the timecode has to be shown as hh:mm.
I thought it would be great to use a String prototype function for this as it would allow me to use code like:
var time = 8.75;
document.write("Meeting at "+time.toTime()); // writes: Meeting at 8:45
So far, I've got that almost working, using:
String.prototype.toTime = function(){
var hrs = this.toString().slice(0,this.indexOf("."));
var min = Math.round(this.toString().slice(this.indexOf("."))/100*60);
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
The problem, though, is that this will only work if the variable time is a string. Otherwise it will give an undefined error.
Would there be any way of applying the prototype to a different object in JavaScript, so that I don't have to use time.toString().toTime()?
Thanks!
Firstly, you can add to the Number prototype. Many people will warn against modifying prototypes, which in many cases is justified. If there is a chance 3rd party scripts will be running alongside yours, it is a danger to modify prototypes.
Secondly, I simplified your code a little, using modulus, and floor to calculate the hrs and mins...
Number.prototype.toTime = function(){
var hrs = Math.floor(this)
var min = Math.round(this%1*60)
min = min<10 ? "0"+min : min.toString();
return hrs+":"+min;
}
var time = 8.25;
console.log("Meeting at "+time.toTime());
You can use Object.prototype.toTime.

Changewheel functionality How it works?

First of all I want share my appreciation for the amazing work done with this snippet (it's really really a cool tool).
I am trying to use mobiscroll in an app that I am currently developing. I love how easy is to use and customize the mobiscroll tool.
What I really find just obscure, is how use the functionality changeWheel. I tried many things but never with success.
What I am trying to accomplish is to change the values of the first wheel (change completely and regenerate the first wheel), when in my second wheel I select (actually what I want is an on change event) one of the two parameters present.
I build up a function that create the arrays for the two wheels, and that change array of the first wheel relatively to the index of the second wheel returned. (I can see that the function works, and that it generate the exact values for the wheels).
How then I can implement this with the onchange event on the inst, using the function changewheel???
Is this function changewheel suppose to do what I am looking for?
To be very clear, think as an example:
first wheel weight of a person
second wheel unit of measurement (kg or Lbs)
If I change on the spot Lbs to Kg, I want that the first wheel reflect the changes (updating the values available) - if for example i set the limit weight between 0 and 80kg the correspondent value in lbs need to be between 0 and 177lbs (the whole conversion is handled separately with another customized function, and it works exactly as I want).
I can't figure out how instead implement the changewheel event....an example or some more deep explanation will be really useful.
Thank you so much
Best
Dinuz
here goes a simple explanation, if you want to update the values of a diferent whell you need to pass the instance of the mobiscroll and call the method options
$(function(){
var filtersMetrics = [{}];
var wheelPosMetrics = []
var wheelPosFunc1 = [];
var wheelPosFunc = [];
wheelPosMetrics[0] = "Connection";
wheelPosMetrics[1] = "Shared";
wheelPosMetrics[2] = "Deleted";
filtersMetrics[0]['Metrics']=wheelPosMetrics;
wheelPosFunc1[0] = "Count";
wheelPosFunc[0] = "Count";
wheelPosFunc[1] = "Sum";
wheelPosFunc[2] = "Avg";
filtersMetrics[0]['Func']=wheelPosFunc1;
var metricsScroller = $("#select").mobiscroll().scroller({
theme : 'android',
display : 'inline',
mode: 'scroller',
wheels: filtersMetrics,
rows: 3,
'onChange' : function(v, i , e){
if(v[0]==1){
filtersMetrics[0]['Func']=wheelPosFunc;
metricsScroller.mobiscroll('option', 'wheels', filtersMetrics);
}else{
filtersMetrics[0]['Func']=wheelPosFunc1;
metricsScroller.mobiscroll('option', 'wheels', filtersMetrics);
}
}
});
});
I have used the 2.5 version
I also wasn't able to get changeWheel to work, but I found a workaround (I'm using Mobiscroll v2.15.1).
In the onChange–Handler you can set the default values dynamicaly:
.
.
.
onChange: function (values) {
// here your logic for the current values
if (/*here your condition*/) {
// Example for three wheels:
var curWheel = ["1", "2", "3"];
// set the default values
$(/*your element*/).mobiscroll("setArrayVal", curWheel, true);
}
},
.
.
.

Javascript Split method not working as expected

I have a method in javascript that use the split method to store the time in an array and then convert the time to seconds. But when I debug, the array always has first 2 elements and ignore the last one. Not sure why?
GetSeconds : function (time) {
var timesecs = 0;
var min = 1;
var timeArray = time.split(ctx.options.separator); //this always contain 2 elements
while (timeArray.length > 0) {
timesecs += min * parseInt(timeArray.pop());
min *= 60;
}
return timesecs;
}
ctx.options.separator is a variable that stores my delimiter. I was trying with ":" and time passed was "00:00:00". This method is called from another method which increments the second.
I tried it in IE, Chrome and Firebug. This behaves differently when I debug through Visual Studio (as this code is in my .net app)
I tried a fiddle and everything works fine there. Are you sure, that ctx.options.separator works as expected?
The problem may be a browser issue if ctx.options.separator is being generated properly.
Which browser are you using?
Use this cross browser method that will make everything work as expected no matter which browser you use.
http://blog.stevenlevithan.com/archives/cross-browser-split
It always has worked for me.

Categories

Resources