singleselect.js 2.0 KB

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