ryanpcmcquen/cheval

Having multiple classes on textarea or button doesn't work

Closed this issue · 7 comments

There's a problem with having multiple classes on the textarea or button.

Easy to reproduce in the sample index.html by adding a class ("other" in example) to the textarea:

<textarea rows="5" class="other text-to-copy-0">Create as many elements as you want, and match them up by name.</textarea>
<p>
  <button class="js-copy-btn-0">Copy text</button>
</p>

This will result in the following error:

Uncaught Error: You don't have a <button> with the class: 'js-copy-btn'. Please check the cheval README.

Thanks for the bug report, I've got this in a fiddle and I'm working on a fix now!

https://jsfiddle.net/ryanpcmcquen/45Lxm5m3/

In the meantime, you can add other classes as long as the text-to-copy-* and js-copy-btn-* ones are first.

@mattiasjahnke I believe I have a fix. Does https://cheval-ryanpcmcquen.c9users.io/index.html function as you expect?

@ryanpcmcquen yepp seems to be working just fine (tested it in my own project aswell).

Great job, dude!

A slightly more elegant solution than mine ;)

var buttons = Array.prototype.slice.call(document.querySelectorAll(
      '[class*=js-copy-btn]'));

var list = [];
for (var i = 0; i < buttons.length; i++) {
   var classNames = buttons[i].classList;
   for (var ic = 0; ic < classNames.length; ic++) {
        var match = classNames[ic].match('js-copy-btn');
        if (match != undefined) {
          var replaced = match.input.replace(/js-copy-btn/, '');
          var textMatch = ''
          if (replaced === '') {
            textMatch = '.text-to-copy'
          } else {
            textMatch = '.text-to-copy' + replaced;
          }
          var textObj = document.querySelector(textMatch);
          list.push({'btn' : buttons[i], 'txt' : textObj});
       }
  }
}

My js-skills are very limited so I had to improvise ;D But I look forward to an updated version so I can throw my hack out the window.

Is the project you are using cheval in publicly accessible? If so, would you mind if I featured it on the README?

No worries, thanks!