Reputation: 10088
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');
}
Upvotes: 0
Views: 1188
Reputation: 90
Try removing the []
from the inputId variable.
I got it to work in your fiddle by changing it to this
var inputId = 'fileInput-' + containerChildrenCount
Upvotes: 1