0

I am attempting to add an input of type 'file' to a form dynamically. Actually the end user can add as many files as they would like to a form, so an array concept is needed. I can inject dynamic elements, but I can't figure out how to dynamically invoke the click of the input element just injected. Also, need to remove the dynamic element if the user chooses cancel on the input element.

I have created a jsfiddle showing the injection but the click event never fires when the trigger is run.

How do I trigger the 'click' event after injecting this element?

jsFiddle Html

<input id='button1' type='button' value='button1'>
<div class='container'>

</div>

jsFiddle JavaScript

$(document).ready(function () {
    $('#button1').on('click', function(event) {
    Button1_Click(event);
  });
});

function Button1_Click(event) {
    var container = $('.container');
  var containerChildren = $(container).children();
  var containerChildrenCount = $(containerChildren).length;
  var inputId = 'fileInput[' + containerChildrenCount + ']';
    $('.container').append('<input id="' + inputId + '" type="file" />');
  $('#' + inputId).trigger('click');
}

1 Answer 1

1

Try removing the [] from the inputId variable.

I got it to work in your fiddle by changing it to this

var inputId = 'fileInput-' + containerChildrenCount

Sign up to request clarification or add additional context in comments.

2 Comments

This works. Not sure why the brackets caused a problem - good find. Any idea how to detect when a user selects cancel in the Open File dialog box?
Sorry, not sure how to detect change in the dialog box. I think the original problem came from allowed chars - quite simple but easy to miss :) Checkout this link: xahlee.info/js/html_allowed_chars_in_attribute.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.