multifield.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // multifield - connects several input fields to each-other
  2. // By Yair Even Or / 2011 / dropthebit.com
  3. ;(function(){
  4. var fixedEvent = 0;
  5. function funnel(e){
  6. fixedEvent++;
  7. var that = this;
  8. setTimeout(function(){
  9. keypress.call(that, e);
  10. fixedEvent = 0;
  11. },0);
  12. }
  13. function keypress(e){
  14. var nextPrevField,
  15. sel = [this.selectionStart, this.selectionEnd];
  16. if( !e.charCode && e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 8 )
  17. return;
  18. // if hit Backspace key when caret was at the beginning, or if the 'left' arrow key was pressed and the caret was at the start -> go back to previous field
  19. if( (e.keyCode == 8 && sel[1] == 0) || (e.keyCode == 37 && sel[1] == 0) )
  20. setCaret( $(this).prev(':text')[0], 100);
  21. // if the 'right' arrow key was pressed and caret was at the end -> advance to the next field
  22. else if( e.keyCode == 39 && sel[1] == this.value.length )
  23. setCaret( $(this).next(':text')[0], 0);
  24. // automatically move to the next field once user has filled the current one completely
  25. else if( e.charCode && sel[1] == sel[0] && sel[0] == this.maxLength )
  26. setCaret( $(this).next(':text')[0], 100);
  27. function setCaret(input, pos){
  28. if( !input ) return;
  29. if (input.setSelectionRange){
  30. input.focus();
  31. input.setSelectionRange(pos, pos);
  32. }
  33. else if( input.createTextRange ){
  34. var range = input.createTextRange();
  35. range.collapse(true);
  36. range.moveEnd('character', pos);
  37. range.moveStart('character', pos);
  38. range.select();
  39. }
  40. }
  41. combine.apply(this);
  42. };
  43. // After each 'change' event of any of the fields, combine all the values to the hidden input.
  44. function combine(){
  45. var hidden = $(this).siblings('input[type=hidden]').val('')[0];
  46. $(this.parentNode).find(':text').each( function(){
  47. hidden.value += this.value;
  48. });
  49. }
  50. $('div.multi').on({'keydown.multifeild':funnel, 'keypress.multifeild':funnel, 'change.multifeild':combine}, 'input');
  51. })();