I'm populating a <select>
element with file names returned by a php script. After uploading a file, I want the <select>
element to automatically select the newly uploaded file. The values of the <option>
elements in the <select>
element are the file names. I'm using jQuery's .prop()
function to set the selected attribute. The element seems to be selected but it immediately de-selects.
Here is my HTML:
<select id="uploadedFilesSelect" name="uploadedFiles" multiple="multiple" onchange="onSelectUploadedFile();"></select>
Javascript:
if (result['filename']) {
$('#uploadedFilesSelect > option:contains(' + result['filename'] + ')').prop('selected', 'selected');
}
The javascript code is called in the success handler of an XMLHttpRequest call to a PHP script which handles the upload.
Observing what happens when I upload a file, I notice that the element scrolls to the new file and briefly selects it, but it then de-selects. Also, you'll notice I have another event handler, onSelectUploadedFile()
, binded to the onchange
event. This event fires when I manually click on a file but not when it "briefly" gets selected.
What am I doing wrong?
Edit: full success handler
function uploadComplete(evt) {
// Parse the returned json string
var result = JSON.parse(evt.target.responseText);
// Refresh the select box
populateSelectWithFiles();
clearFileInput();
// Select the uploaded file in the select element
if (result['filename']) {
$('#uploadedFilesSelect > option:contains(' + result['filename'] + ')').prop('selected', 'selected');
}
}
The function populateSelectWithFiles()
calls a php script to add the file names to the select
element.
The function clearFileInput()
just clears the file input element by creating a new one and replacing the on the page.
You will have to trigger the onchange event yourself, .prop() will not trigger this. You can use:
$('#uploadedFilesSelect').trigger('change');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.