I have 5 spinners which are almost working perfectly, there is just one little glitch I cannot overcome.
What is suppose to happen is that if a spinner is blank, whatever the previous number was in THAT spinner, it will display that previous number.
Instead what it is doing is that any previous number that has been entered in ANY of the 5 spinners, it displays that number in the blank spinner.
So how can I get it so that it displays the previous number from that spinner if a spinner is blank rather than displaying the last previous number entered from any spinner in the blank spinner?
Below is my spinner code:
function Spinner(elem,min, max){
this.elem = elem;
this.elem.value = min;
this.min = min;
this.max = max;
this.timer;
this.speed = 150; //milliseconds between scroll values
var selfO = this;
this.elem.onkeyup = function(){
var regex = /^[0-9]*$/;
if(!regex.test(selfO.elem.value)){
selfO.elem.value = selfO.elem.value.substring(0,selfO.elem.value.length-1);
return;
}
selfO.validateValue();
}
this.validateValue = function(){
if(Number(selfO.elem.value) > selfO.max) {selfO.elem.value = selfO.max;}
if(Number(selfO.elem.value) < selfO.min) {selfO.elem.value = selfO.min;}
}
this.stopSpinning = function(){
clearTimeout(selfO.timer);
}
this.spinValue = function(dir){
selfO.elem.value = Number(selfO.elem.value) + dir;
selfO.validateValue();
selfO.timer = setTimeout(function(){selfO.spinValue(dir);},selfO.speed);
}
};
window.onload=function(){
//create the Spinner objects
var SpinnerHours = new Spinner(document.getElementById('txtHours'),0,23);
var SpinnerMins = new Spinner(document.getElementById('txtMins'),0,59);
var SpinnerSecs = new Spinner(document.getElementById('txtSecs'),0,59);
var SpinnerWeight = new Spinner(document.getElementById('txtWeight'),0,100);
var SpinnerQuestion = new Spinner(document.getElementById('txtQuestion'),0,100);
document.getElementById('txtHours').onblur = function(){ this.value = cleanSpin(this.value);}
document.getElementById('txtMins').onblur = function(){ this.value = cleanSpin(this.value);}
document.getElementById('txtSecs').onblur = function(){ this.value = cleanSpin(this.value);}
document.getElementById('txtWeight').onblur = function(){ this.value = cleanSpin(this.value);}
document.getElementById('txtQuestion').onblur = function(){ this.value = cleanSpin(this.value);}
function cleanSpin(obj) {
if(obj > 0) {
var str = obj.replace(/^0*/,'');
lastSpin = str;
return str;
}
else {
return lastSpin;
}
}
var lastSpin = 1;
The problem is that your
lastSpinvariable, and indeed, yourcleanSpin()function, are in the global scope, and thus shared across all Spinner instances.Instead, you should try adding the
cleanSpinmethod, or a variant thereof, to theSpinner“class”, so that it becomes local to that instance of the Spinner.EDIT: Here is the complete Javascript to illustrate what I meant. I have not tested this at all, as I do not have the rest of the code needed to do so, but hopefully you can see what I have changed: