singleselect.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. (function ($) {
  2. $.fn.singleSelect = function () {
  3. return this.each(function (i, select) {
  4. var input = $('<input/>'),
  5. inputTooltip = $(select).attr('data-inputtitle');
  6. if (inputTooltip){
  7. input.attr('title', inputTooltip);
  8. }
  9. select = $(select);
  10. input.css('position', 'absolute');
  11. input.css({
  12. 'box-sizing': 'border-box',
  13. '-moz-box-sizing': 'border-box',
  14. 'margin': 0,
  15. 'width': (select.width() - 5) + 'px',
  16. 'height': (select.outerHeight() - 2) + 'px',
  17. 'border': 'none',
  18. 'box-shadow': 'none',
  19. 'margin-top': '1px',
  20. 'margin-left': '1px',
  21. 'z-index': 1000
  22. });
  23. input.hide();
  24. $('body').append(input);
  25. select.on('change', function (event) {
  26. var value = $(this).val(),
  27. newAttr = $('option:selected', $(this)).attr('data-new');
  28. if (!(typeof newAttr !== 'undefined' && newAttr !== false)) {
  29. input.hide();
  30. select.data('previous', value);
  31. } else {
  32. event.stopImmediatePropagation();
  33. // adjust offset, in case the user scrolled
  34. input.css(select.offset());
  35. input.show();
  36. if ($.fn.tipsy){
  37. input.tipsy({gravity: 'n', trigger: 'manual'});
  38. input.tipsy('show');
  39. }
  40. select.css('background-color', 'white');
  41. input.focus();
  42. }
  43. });
  44. $(select).data('previous', $(select).val());
  45. input.on('change', function () {
  46. var value = $(this).val();
  47. if (value) {
  48. select.children().attr('selected', null);
  49. var existingOption = select.children().filter(function (i, option) {
  50. return ($(option).val() == value);
  51. });
  52. if (existingOption.length) {
  53. existingOption.attr('selected', 'selected');
  54. } else {
  55. var option = $('<option/>');
  56. option.attr('selected', 'selected').attr('value', value).text(value);
  57. select.children().last().before(option);
  58. }
  59. select.val(value);
  60. select.css('background-color', null);
  61. input.val(null);
  62. input.hide();
  63. select.change();
  64. } else {
  65. var previous = select.data('previous');
  66. select.children().attr('selected', null);
  67. select.children().each(function (i, option) {
  68. if ($(option).val() == previous) {
  69. $(option).attr('selected', 'selected');
  70. }
  71. });
  72. select.removeClass('active');
  73. input.hide();
  74. }
  75. });
  76. input.on('blur', function () {
  77. $(this).change();
  78. if ($.fn.tipsy){
  79. $(this).tipsy('hide');
  80. }
  81. });
  82. });
  83. }
  84. })(jQuery);