Reputation:
So im building this page where i am including a file input using ajax, but i am not able to trigger jquery when a the file is changed. is this a normal thing or should this just work? I am trying to get the filename displayed in the input type text field.
My ajax call
$('.wijzigproduct').on('click', function () {
var productvalue = $(this).val();
$.ajax({
url: "includes/productwijzigen.php?q=" + productvalue,
success: function (result) {
$('#editproduct').html(result);
}
});
});
My input fields:
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Bladeren… <input type="file" name="imgInpnew" id="imgInpnew">
</span>
</span>
<input type="text" class="form-control" id='imgOutpnew' readonly>
</div>
<img id='imgshownew'/>
My jquery:
$('#imgInpnew').change(function () {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
Upvotes: 1
Views: 1318
Reputation: 7970
The change()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future.
Since you have generated DOM using jQuery, you have to create a "delegated" binding by using on()
. Here is the solution base on the code you have provide on jsfiddle.net/a70svxto
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
}
});
$('#div').on('change', '#imgInpnew', function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'></div>
Upvotes: 1
Reputation: 571
well you are attaching the change event to a not existing element in the DOM.
you have to first add the element into the DOM and then attach the event to the element
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
$('#imgInpnew').change(function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
}
});
https://jsfiddle.net/a70svxto/
Upvotes: 1