Posted By

jatkins on 04/03/12


Tagged

data input increment values units decrement


Versions (?)

Increment/decrement input fields with values that have units


 / Published in: JavaScript
 

Released into the public domain.

  1. function changeField(fieldToChange, incVal, boundValues, validUnits) { // boundValues indices: 0 is max, 1 is min, 2 is "max set?", 3 is "min set?"
  2. for(var i=0;i<2;i++) {
  3. if(typeof boundValues[i]=='undefined'||(typeof boundValues[i]!='undefined'&&isNaN(boundValues[i])))
  4. boundValues[i] = Number.POSITIVE_INFINITY * (i==1?-1:1);
  5. else
  6. boundValues[i+2] = true;
  7. }
  8.  
  9. newValue = Math.round((parseFloat(fieldToChange.value) + (incVal ? 1 : -1))*100)/100;
  10. if(newValue > boundValues[0] || newValue < boundValues[1]) // check if out of bounds
  11. newValue = incVal ? (boundValues[3] ? boundValues[1] : 0) : (boundValues[2] ? boundValues[0] : 0);
  12.  
  13. unitsUsed = fieldToChange.value.replace(/[0-9\-\.]/g, '');
  14. fieldToChange.value = (isNaN(newValue) || find_index(validUnits, unitsUsed) == -1 ? '0' : newValue) + unitsUsed;
  15. return fieldToChange.value;
  16. }

Report this snippet  

You need to login to post a comment.