Enclose argument in method called by onchange in input with \" and assign it to div to become messy

Lionsure 2020-06-17 Original by the website

Uploading files with "input type=file" needs to be completed by using javascript. The execution process of the client is probably like this: the user clicks "Browse" to select the file to be uploaded and triggers the "onchange" event of "input", and calls a method in the "onchange". The method is responsible for submitting the file to the server, and the server completes the file upload.

This method needs to rewrite "input type=file" after uploading the file each time. This involves assigning "input type=file" to its parent. The assignment process involves triple strings, that is, "first layer"second layer"third layer""", if you enclose the character string of the third layer with the escape character \", the "input type=file" will be messy and unresponsive, and if it is converted to single quotes, it will not be messy.


1. Enclose the argument in method to be called by onchange in input type=file with \" and assign it to div to become messy and unresponsive

If there is "input type=file" as follows:

<div id="divId"><input type="file" id="uploadImageId" name="uploadImageId" onchange="uploadImage(\"divId\")"/></div>

If there is "input type=file" as follows:

document.getElementById("divId").innerHTML = "<input type=\"file\" id=\"uploadImageId\" name=\"uploadImageId\"onchange=\"uploadImage(\"divId\")\" />";


After uploading the file once, assign the "input type=file" to the div again:

<input name="uploadImageId" id="uploadImageId" onchange="uploadImage(" type="file" divId")"="">

The main problem is that the "type=file" of the "input" went to the parentheses of method to be called by onchange to change the argument, making the arguments messy without executing the onchange event.


2. The solution

The solution is very simple, just change the argument's escape character \" to single quotes ' and it won't be messy anymore, the code is changed to:

document.getElementById("divId").innerHTML = "<input type=\"file\" id=\"uploadImageId\" name=\"uploadImageId\" onchange=\"uploadImage('divId')\" />";

In fact, the escape character cannot be used twice, that is, the character string enclosed by the escape character in which there are strings to be enclosed by the escape characters are not allowed.