bootstrap-table-copy-rows.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * @author Homer Glascock <HopGlascock@gmail.com>
  3. * @update zhixin wen <wenzhixin2010@gmail.com>
  4. */
  5. const Utils = $.fn.bootstrapTable.utils
  6. $.extend($.fn.bootstrapTable.defaults.icons, {
  7. copy: {
  8. bootstrap3: 'glyphicon-copy icon-pencil',
  9. materialize: 'content_copy',
  10. 'bootstrap-table': 'icon-copy'
  11. }[$.fn.bootstrapTable.theme] || 'fa-copy'
  12. })
  13. const copyText = text => {
  14. const textField = document.createElement('textarea')
  15. $(textField).html(text)
  16. document.body.appendChild(textField)
  17. textField.select()
  18. try {
  19. document.execCommand('copy')
  20. }
  21. catch (e) {
  22. console.log('Oops, unable to copy')
  23. }
  24. $(textField).remove()
  25. }
  26. $.extend($.fn.bootstrapTable.defaults, {
  27. showCopyRows: false,
  28. copyWithHidden: false,
  29. copyDelimiter: ', ',
  30. copyNewline: '\n'
  31. })
  32. $.fn.bootstrapTable.methods.push(
  33. 'copyColumnsToClipboard'
  34. )
  35. $.BootstrapTable = class extends $.BootstrapTable {
  36. initToolbar (...args) {
  37. super.initToolbar(...args)
  38. const $btnGroup = this.$toolbar.find('>.columns')
  39. if (this.options.showCopyRows && this.header.stateField) {
  40. this.$copyButton = $(`
  41. <button class="${this.constants.buttonsClass}">
  42. ${Utils.sprintf(this.constants.html.icon, this.options.iconsPrefix, this.options.icons.copy)}
  43. </button>
  44. `)
  45. $btnGroup.append(this.$copyButton)
  46. this.$copyButton.click(() => {
  47. this.copyColumnsToClipboard()
  48. })
  49. this.updateCopyButton()
  50. }
  51. }
  52. copyColumnsToClipboard () {
  53. const rows = []
  54. $.each(this.getSelections(), (index, row) => {
  55. const cols = []
  56. $.each(this.options.columns[0], (indy, column) => {
  57. if (
  58. column.field !== this.header.stateField &&
  59. (!this.options.copyWithHidden ||
  60. this.options.copyWithHidden && column.visible)
  61. ) {
  62. if (row[column.field] !== null) {
  63. cols.push(Utils.calculateObjectValue(column, this.header.formatters[indy],
  64. [row[column.field], row, index], row[column.field]))
  65. }
  66. }
  67. })
  68. rows.push(cols.join(this.options.copyDelimiter))
  69. })
  70. copyText(rows.join(this.options.copyNewline))
  71. }
  72. updateSelected () {
  73. super.updateSelected()
  74. this.updateCopyButton()
  75. }
  76. updateCopyButton () {
  77. this.$copyButton.prop('disabled', !this.getSelections().length)
  78. }
  79. }