Miguel Fernandez Miguel Fernandez - 10 months ago 37
Javascript Question

How to concatenate a variable with ' ' in jQuery

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])">


<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


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])">';