I have an onclick
problem. I searched the internet, but the people who had the same problem do not fully explain how they fixed the problem. I cannot figure out what goes on here.
I am supposed to make a button called "Load New", when clicked it showed allow a user to select a file.
HTML
<input type="button" class="clear-button" onclick="clearB()" value="Clear Board" /><br /><br />
<input type="button" value="Load Game To Board" onclick="LoadGame()" />
<input type="button" id="get_file" onclick="n();" value="Load New Game">
<input type="file" id="my_file">
CSS
#my_file {
display: none;
}
Javascript
function n() {
if (document.getElementById('get_file') != null) {
document.getElementById('get_file').onclick = function() {
document.getElementById('my_file').click();
}
//LoadGame(); //triggers this function without allowing the user to open file.
}
}
Lastly I cannot put a function to manipulate the contents of the file in the function n(). No matter where I put it, it triggers the function without opening the file-select dialog.
The dialog is not visible after the first click because the first click attaches the event handler an anonymous function to open my_file
but it does not execute it.
The second click executes the anonymous function since it is already attached. This fires the click event for my_file
:
function showFileUpload(){
document.getElementById('get_file').onclick = function() {
document.getElementById('my_file').click()
}
}
This version fires the click event for my_file
function showFileUpload_2(){
document.getElementById('my_file').click()
}
This is the html
<input type="button" id="get_file"
onclick="showFileUpload_2();" value="Load New Game">
<input type="file" id="my_file">
There is no need for this function -
document.getElementById('get_file').onclick = function() {
.....
}
Change your script as
<script>
function n(){
if(document.getElementById('get_file') != null){
//document.getElementById('get_file').onclick = function() { //comment this function
document.getElementById('my_file').click()
//}
//LoadGame(); //triggers this function without allowing the user to open file.
}
}
</script>
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.