Aitor Chicharro
Aitor Chicharro

Reputation: 73

Input file, click no working.. No event

I have a problem, generate an input file type, the click event does not work. Input generate in HTML works natively clicking, or Click events on jquery or more. But when I try something like ..

$('body').append('<input type="file" id="asd" />')

None of these works, and even doing click natively, does not work, it appears, but it seems to not have any events.

document.getElementById('asd').click()
$('#asd').click()
document.getElementById('asd').dispatchEvent(new Event('click'));

That may be happening? It does not work in Chrome or Firefox ...

Even running these commands in Stackoverflow this does not work, so it can not be...

Sorry for my english.

Upvotes: 1

Views: 9213

Answers (4)

Ardit Maloku
Ardit Maloku

Reputation: 1

You can't click on an appended element without calling the click event like this:

$(document).on('click', '#asd', function() {
      // This will work!
});

Upvotes: 0

tkay
tkay

Reputation: 1726

Its not possible to emulate a file input click event without a user action. If you want to hide the file input then you'll have to add a button for the user to click.In its click event you should emulate the file input's click event. In other words if you are trying to trigger a file input click from an event which is not trusted by the browser then the click wont work. Check this question and its answer. Trigger click on input=file on asynchronous ajax done()

$('body').append("<input style='visibility:hidden;' type='file' id='asd'/><button id='trigger'>trigger file input</button>")

$('#trigger').on('click',function(){$('#asd').click()});
#trigger{
background:red;
  color:white;
  padding:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

File input can't be automatically clicked without any user interaction due to security purpose. It will be very crappy if a page activates anything itself when the page loads.

You can use label to click file input by user like following.

$('body').append('<input type="file" id="asd" /><label for="asd">Click</label>');

Upvotes: 1

FelixHo
FelixHo

Reputation: 1304

The problem is that the second "input" element is added dynamically and the click binding happens before the second "input" element exists. That's why it has no affect on it.You can attach the handler to each anchor before you insert it.

try this code to bind your click event:

$('body').on('click', '#ads', function(e){
    ...
});

btw, give your input element a class name is better , and bind the click event with class name like '.class'

Upvotes: 1

Related Questions