1

I rewrite file input by code on: http://jsfiddle.net/b9rtk/ but when we click at dynamic button 'Add one more file' the JavaScript click() (line 13) doesn't work.

How to use JavaScript click() method (not jQuery) for dynamic created elements?

$('input[type=file]').on('change', function () {
    code = '<fieldset>' + $(this).parents('fieldset').html()
        .replace('Browse and select file', 'Add one more file') + '</fieldset>';
    $(this).parents('fieldset').after(code);
});
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
kicaj
  • 2,881
  • 5
  • 42
  • 68

1 Answers1

1

How to use JavaScript click() method (not jQuery) for dynamic created elements?

I've re-written it in VanillaJS. Not the only way to re-write it, I'm sure.

(function () {
    var inputs = document.getElementsByTagName('input'),
        fn = function () {
            var html = this.parentNode.innerHTML.replace(
                    'Browse and select file',
                    'Add one more file'
                ),
                d = document.createElement('div'),
                df = document.createDocumentFragment();
            html = '<fieldset>' + html + '</fieldset>';
            d.innerHTML = html;
            while (d.childNodes.length)
                df.appendChild(d.childNodes[0]);
            if (this.parentNode.parentNode.nextSibling) // <form> is 3 parents up
                this.parentNode.parentNode.parentNode.insertBefore(
                    df,
                    this.parentNode.parentNode.nextSibling
                );
            else
                this.parentNode.parentNode.parentNode.appendChild(df);
        },
        i = inputs.length;
    while (i--) {
        if (inputs[i].getAttribute('type').toLowerCase() === 'file')
            inputs[i].addEventListener('change', fn);
    }
}());
Paul S.
  • 64,864
  • 9
  • 122
  • 138