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);
});
6
  • 3
    Why don't you want to use jQuery? You're using it for everything else... Commented Sep 13, 2013 at 12:10
  • In this example on('click') doesn't work, I don't know why!? Commented Sep 13, 2013 at 12:17
  • 1
    You should post a question asking why your click doesn't work, rather than how to do it outside of jQuery Commented Sep 13, 2013 at 12:17
  • 1
    Have a look at this: stackoverflow.com/questions/793014/jquery-trigger-file-input Reason you can't trigger click is because the input is hidden. Commented Sep 13, 2013 at 12:19
  • @sunn0: is set to display my inputs, but this doesn't work Commented Sep 13, 2013 at 12:38

1 Answer 1

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);
    }
}());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.