Bharanikumar
Bharanikumar

Reputation: 25733

Getting undefined after value selected

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

Answers (3)

Rayon
Rayon

Reputation: 36609

One needs to use change listener to get the value from the input type='file'. In your example there is not attribute value in your element hence it is returning undefined.

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

Himesh Aadeshara
Himesh Aadeshara

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

Refer Document

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

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

Related Questions