Reputation: 25733
var input = $(document.createElement('input'));
input.attr("type", "file");
input.attr("id", "files");
input.attr("name", "files[]");
input.trigger('click');
alert(input.attr("value"));
The above script open the file browser window and i am able to select the file as well, but in alert am seeing undefined, how to get actual file name in the alert.
Upvotes: 1
Views: 68
Reputation: 36609
One needs to use
change
listener to get the value from theinput type='file'
. In your example there is not attributevalue
in your element hence it is returningundefined
.You have the freedom to use
$("<input />")
or$(document.createElement('input'));
but if you are doing it jQuery way then go for the former.
Try this:
var input = $("<input />");
input.attr("type", "file");
input.attr("id", "files");
input.attr("name", "files[]");
$('body').append(input);
input.on('change', function() {
alert(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 2121
hi you could either use
var input = document.createElement('input');
or
var input = $("<input />");
you are having code wrong by syntax
please refer the how you can add element
Upvotes: 0
Reputation: 167162
Just use this:
var input = $("<input />");
And also bind the alert with the change
event.
Snippet
$(function () {
var input = $("<input />");
input.attr("type", "file");
input.attr("id", "files");
input.attr("name", "files[]");
input.trigger('click');
$("body").append(input);
input.change(function () {
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Upvotes: 5