1
0

singleselect.js 2.6 KB

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