Reputation:
Hello I am trying to create a input with a function onchange with Ajax using jQuery this is the input:
<input type="file" class="hidden-print btn-sm" id="btn1"
onchange="document.getElementById('blah').src = window.URL.createObjectURL(this.files[0])">
EDIT:
<img id="blah" alt="Image 1" class="img-responsive" />
And in my js I have this:
var blah = 'blah';
html += '<input type="file" class="hidden-print btn-sm" id="btn1" onchange="document.getElementById('+ blah +').src = window.URL.createObjectURL(this.files[0])">';
I also try with
getElementById(' + "blah" + ') rest of the code...
But I get this console error:
Cannot set property 'src' of null. I know that is because the ('blah') problem because in HTML code works fine.
Here is the code if you want to see it
Upvotes: 3
Views: 90
Reputation: 337560
You need to include the quotes around the variable value when it's appended to the string. To do that you need to escape the quotes that are in the string so they are not interpreted as delimiting the string, to do that you can use \'
. Try this:
html += '<input type="file" class="hidden-print btn-sm" id="btn1" onchange="document.getElementById(\''+ blah + '\').src = window.URL.createObjectURL(this.files[0])">';
Upvotes: 5