skip to Main Content

I’m having issues with JavaScript not detecting the click event on a button. Here is my HTML code:

<input type="button" value="Upload"
       id="filemanagement_uploadbutton[0]"
       name="filemanagement_uploadbutton"
       onclick="javascript:uploadFiles();"
       >

Here is my JavaScript code (with console.log commands for error checking):

let fileButtons = document.getElementsByName('filemanagement_uploadbutton');
console.log(fileButtons.length);    // returns 2, since I have two buttons
console.log(fileButtons[0].id);     // returns filemanagement_uploadbutton[0]
console.log(fileButtons[0].type);   // returns button
console.log(fileButtons[0].click);  // returns javascript:uploadFiles();
fileButtons[0].click();

I’ve also tried:

let fileButton = document.getElementsByName('filemanagement_uploadbutton')[0];
fileButton.click();

Both of these result in the error:

Uncaught TypeError: fileButtons[0].click is not a function

or

Uncaught TypeError: fileButton.click is not a function

How is it telling me that click is not a function on the element that it’s telling me the click function is javascript:uploadFiles(); literally one element above?

Edit: I’ve also tried these variations:

let fileButtons = document.getElementsByName('filemanagement_uploadbutton')[0];   //obviously the command for fileButtons[0].length won't work here as expected, so I comment it out
let fileButton = document.getElementById('filemanagement_uploadbutton[0]');

with the appropriate changes to the code below when I reference them.

2

Answers


  1. Instead of using the inline HTML "onclick" function, you could try removing it and using an event listener in your JavaScript instead.

    let fileButtons = document.getElementByName('filemanagement_uploadbutton');
    
    if (fileButtons.length > 0) {
    fileButtons[0].addEventListener('click', uploadFiles);
    fileButtons[0].click();
    }
    
    Login or Signup to reply.
  2. You are need to have your code something like this.

    First you need get the element by id using document.getElementById('filemanagement_uploadbutton[0]')

    and then add the add event listener.

    addEventListener('click', () => {
        // your code goes here
    });
    
    document.getElementById('filemanagement_uploadbutton[0]').addEventListener('click', () => {
        alert('hi');
    });
    <button id="filemanagement_uploadbutton[0]" name="filemanagement_uploadbutton">Upload</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search