This is because INPUT was inserted later, this is known as a dynamic element in Javascript.
Multiple native functions (eg.click) or not (eg.Select2), do not work before the element exists, in fact all functions work in such a way.
The alternative is to use:
$('#div').load("page.php",{foo : bar}, function(){ $('#foto').fileinput(); } );
I haven’t read all the documentation of JS File Input, I took a look at it this time.
But, the idea is to initialize the input after loading the content.
However the problem is not isolated to "fileinput", so the important thing is that you understand about the dynamic elements themselves.
Dynamical elements
Note this problem, similar:
$('button').click(function(){
alert('Funcionou!');
$('body').append('<br><button>Isso agora não funciona</button>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Isso funciona</button>
</body>
The reason is the same as your problem!
The .click only reaches the first button, which was already there when Jquery was triggered.
But if you do:
function button(){
$('button').click(function(){
alert('Funcionou!');
$('body').append('<br><button>Isso agora não funciona (#SQN)</button>');
$('button').off();
button();
});
}
button();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Isso funciona</button>
</body>
Each insertion will again declare the .click this way will be reading/identified/monitoring the inserted object dynamically. If you choose to do this observe the .off(), ignore this will duplicate the action of the existing buttons.
In the specific case of this example, there is something better to be done:
$('body').on('click', 'button', function(){
alert('Funcionou!');
$('body').append('<br><button>Isso agora não funciona (#SQN)</button>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Isso funciona</button>
</body>
The .on() monitors the body previously defined. Body is not dynamic (except if creating a new body, but it is not common). Even so, dynamic elements can be inserted inside the body, like this button. This way by clicking inside the body Jquery checks if the clicked element is a button. This allows you to insert numerous elements of button dynamically, provided that within the body.
Interesting, I get the concept of it. Thanks a lot for the help, I’ll give a read on the fileinput doc, I would have a few more arguments to work the way I want, but that’s what you said. Was worth too much!
– Gustavo Carvalho