Задача: qForms, библиотека типичного функционала валидации/построения/связки html-форм
Исходник: bits.js :: qForms api-139, язык: javascript [code #151, hits: 10073]
автор: - [добавлен: 28.05.2006]
  1. // define Field getBits(); prototype
  2. function _Field_getBits(useValue){
  3. var isCheckbox = (this.type == "checkbox") ? true : false;
  4. var isSelect = (this.type == "select-multiple") ? true : false;
  5.  
  6. if( !isCheckbox && !isSelect && (this.obj.length > 0) ) return alert("This method is only available to checkboxes or select boxes with multiple options.");
  7. var useValue = _param(arguments[0], false, "boolean");
  8.  
  9. var iBit = 0;
  10. // loop through all checkbox elements, and if a checkbox is checked, grab the value
  11. for( var i=0; i < this.obj.length; i++ ){
  12. // if the option is checked, then add the 2 ^ i to the existing value
  13. if( isCheckbox && this.obj[i].checked ){
  14. // append the selected value
  15. iBit += (useValue) ? parseInt(this.obj[i].value, 10) : Math.pow(2, i);
  16. } else if( isSelect && this.obj.options[i].selected ){
  17. iBit += (useValue) ? parseInt(this.obj[i].value, 10) : Math.pow(2, i);
  18. }
  19. }
  20. return iBit;
  21. }
  22. Field.prototype.getBits = _Field_getBits;
  23.  
  24. // define Field setBits(); prototype
  25. function _Field_setBits(value, useValue){
  26. var isCheckbox = (this.type == "checkbox") ? true : false;
  27. var isSelect = (this.type == "select-multiple") ? true : false;
  28.  
  29. if( !isCheckbox && !isSelect && (this.obj.length > 0) ) return alert("This method is only available to checkboxes or select boxes with multiple options.");
  30. var value = _param(arguments[0], "0");
  31. var useValue = _param(arguments[1], false, "boolean");
  32.  
  33. var value = parseInt(value, 10);
  34. // loop through all checkbox elements, and if a checkbox is checked, grab the value
  35. for( var i=0; i < this.obj.length; i++ ){
  36. // if the bitand returns the same as the value being checked, then the current
  37. // checkbox should be checked
  38. var j = (useValue) ? parseInt(this.obj[i].value, 10) : Math.pow(2, i);
  39. var result = ( (value & j) == j) ? true : false;
  40. if( isCheckbox ) this.obj[i].checked = result;
  41. else if( isSelect ) this.obj.options[i].selected = result;
  42. }
  43. // if the value provided is greater then the last bit value, return false to indicate an error
  44. // otherwise return true to say everything is ok
  45. return (value < Math.pow(2, i)) ? true : false;
  46. }
  47. Field.prototype.setBits = _Field_setBits;
  48.  
  49.  
/******************************************************************************
qForm JSAPI: Bits Extensions Library

Author: Dan G. Switzer, II
Build: 101
******************************************************************************/
Тестировалось на: IE 6.0 SP2, Mozilla FF 1.5, Opera 8.5

+добавить реализацию