Execute JavaScript function once instead of repeatedly

I am seeking a JavaScript code that can verify the size of an input file before uploading whenever the user changes the input value (i.e. whenever a file is selected for upload).

Here is what I have come up with so far:

var file = document.getElementById("myFile");
    file.addEventListener('change', function() {
        if (this.files[0].size > 2*1024*1024) {
            alert('Max file size is 2 MB');
            file.removeAttribute('value');
            file.parentNode.replaceChild(file.cloneNode(true),file);
            }
        }
    );

The accompanying HTML code is as follows:

<form action="?" method="post">
    <input type="file" id="myFile" name="myFile" />
    <input type="submit" value="upload" />
</form>

If I keep the JavaScript code as is, it does not function properly. However, when I modify it like this

window.onload = function() {

      // Code remains the same

}

it works, but only for the first file that the user selects.

How can I adjust it to ensure it functions every time a user selects a file? (if possible without jQuery)

Answer №1

You don't have to duplicate the node, just assign an empty value;

file.value = '';

Check out this functional code snippet

document.getElementById("myFile").addEventListener('change', function() {
  if (this.files[0].size > 2*1024*1024) {
    alert('Maximum file size is 2 MB');
    this.value='';
  }
});
<form action="?" method="post">
    <input type="file" id="myFile" name="myFile" />
    <input type="submit" value="upload" />
</form>

Answer №2

According to the documentation on cloning nodes found at this link:

When you clone a node, it duplicates all attributes and their corresponding values, including inline listeners. However, bear in mind that event listeners added using addEventListener() are not copied.

If you remove an element with an event handler and replace it with one lacking a listener, be sure to reapply the event listener by calling addEventListener again. It's advisable to store the result of file.cloneNode(true) in a variable so that you can add the event listener and pass it to replaceChild function accordingly.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

incorporating a dynamic parameter into the payload of an AJAX post request

I'm currently working on a function call where I want to extract the value of the variable data and place it in the data section of the function. However, despite my efforts, I haven't been successful so far. In PHP, I am attempting to retrieve t ...

What is the procedure for removing an item from an array in MongoDB using its unique identifier?

I am in the process of constructing a compact movie-reference database, and I would like to implement a feature that allows me to remove an item from an array. To provide some context and background information, here is the schema I am working with: cons ...

Mastering the art of utilizing defer/async attributes in script tags effectively

When I add the "defer" attribute to all external js files, Owl Carousel fails to load and shows an error that "$" is not defined. However, if I remove the defer attribute from the script tag, everything works fine without any errors. Unfortunately, I am un ...

What are some ways to display multiple divs within a single popup window?

I am attempting to create the following layout: https://i.sstatic.net/OzE98.png Here is what I have been able to achieve: https://i.sstatic.net/7GxdP.png In the second picture, the divs are shown separately. My goal is to display the incoming data in a ...

Problem with the swipe direction in Flexslider when right-to-left language

I have integrated the flexslider with rtl support from a website called rtl-this.com. However, I am facing an issue where when swiping the slider on touch screens, it moves in the opposite direction. Can anyone suggest a solution to fix this problem? ...

Show data from a Node.js server in its original format within an AngularJS application

Currently, I am using the angular fullstack generator to develop a web application. One issue I am facing is sending file data from the Node.js server to display on the front end. The problem arises because the data is being sent in an unformatted manner, ...

Transferring a JSON array from Google App Engine to Cloud Storage using GO

I am attempting to upload a JSON array to Google Cloud Storage, which is posted by an App Engine application using the code below: saveData : function saveData() { var _this = this, save = this.shadowRoot.querySelector('#save-data'), ...

An issue arises when attempting to write to the database specifically when the model is imported from a separate file

There seems to be an issue with saving the model to the database when it's imported from another file. The error message received is: MongooseError: Operation users.insertOne() buffering timed out after 10000ms at Timeout. (/var/www/bhp_2/server/nod ...

Enzyme examination: Error - anticipate(...).find was not recognized as a function

What is the reason for .find not being recognized as a function in the code snippet below? import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import { AuthorizedRoutesJest } from ...

Eliminate items from one array when there is a corresponding match in a separate array using JavaScript

I am working with 2 JavaScript arrays First Array var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}]; Second Array var unSel ...

Having trouble displaying a popup dialog box in ASP.NET using JavaScript

I am trying to implement a popup dialog box in ASP.NET using JavaScript, but it's not working as expected! Below is the code I am using: <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal< ...

Using Angular to sort arrays based on the values in a separate array

I have a unique setup where there is a table containing select options in each row. The value of the select option changes based on the 'dataType' specified for that particular row. Here is an example of my Table Array: { 'name':' ...

"Exploring the v-autocomplete functionality: Recognizing when no results are found and incorporating a personalized

I am using a Vuetify component to search for users in a list. If the search yields no results, I want to display a button that allows the user to create a new user: <v-autocomplete v-model="event.user" :items=" ...

The login form is experiencing issues with submission when utilizing the submitFormHandler in ReactJS

In my single-page application, I'm working on creating a separate login page that will redirect the authenticated user to the main application. However, I'm encountering an issue where my submitFormHandler is not being invoked. The purpose of aut ...

Having trouble retrieving the response from Jquery ajax with ajaxoptions

Struggling to utilize jQuery effectively. function fetchData(Id) { var ajaxOptions = { url: 'Api/Client/Get?Id=' + id, type: 'GET', dataType: 'json' }; return $.ajax(ajaxOptions).done().fa ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

My code gets disrupted when I switch between ids and classes

I'm currently learning about javascript and jquery, attempting to implement various scripts. I successfully executed the following script: jQuery(document).ready(function($) { var scroll_start = 0; var startchange = $('#homepage-header' ...

Generate JSON key-value pairs by nesting them in D3

Looking to convert a JSON into key-value pairs using d3.nest(). The initial JSON structure is as follows: [ { "Country": "Mexico", "Climate": 100, "Safety Index": 50, "Life Expectancy": 80, "Corruption": 30, "Per Capita Income": ...

loading xml data into a table partially using jquery

Currently, I am utilizing AJAX to load and parse XML data. I have constructed a table where I am inserting the data from the XML using a loop. The issue lies in the fact that only around 3000 rows are being inserted into the table even though the XML conta ...

Using 2 parameters, ExternalInterface.addCallback

Attempting to pass 2 variables from JavaScript to Flash, I came up with a solution in ActionScript 3 to try and receive them. ExternalInterface.addCallback("callAs", muscle, tension); However, this method resulted in an error: Error: 1137 - Incorrect nu ...