Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions.

$(function() {
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
               var reader = new FileReader();

               reader.onload = function(event) {
                 $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                 }

                 reader.readAsDataURL(input.files[i]);
                 }
              }
          };

          $('#upload-image').on('change', function() {
              imagesPreview(this, 'img.image');
       });
   });
div.img_container {
    max-width: 1px;
    max-height: 1px;
}
img.image {
    width: 1px;
    height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
   <input id='upload-image' type='file' name='files[]' multiple>
   <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

Answer №1

Make sure to update the src of the image and not append it into another image:

$(function() {
  var imagesPreview = function(input, img) {

    if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $(img).attr('src', event.target.result)
        }

        reader.readAsDataURL(input.files[i]);
      }
    }

  };

  $('#upload-image').on('change', function() {
    imagesPreview(this, 'img.image');
  });
});
img.image {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
  <input id='upload-image' type='file' name='files[]' multiple>
  <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

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

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

What is the best way to showcase a person's first and last name in individual text fields?

Within a drop-down menu, each option is formatted like the following example: scomp23 - Jack Turner By utilizing the code snippet below: var text = $(this).find('option:selected').text(); var split = text.split(' - '); $('#curre ...

Loop through the .getJSON response using jQuery

I've searched high and low for an answer to my question, but I can't seem to find one. My issue is with iterating over a JSON array (and its object) using jQuery's .each() method to print out all the values. Here is the JSON structure: { ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

JavaScript function execution fails following an AJAX request

One of my functions is functioning properly with the alert: function RequestNext() { var xhr = getXMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { ...

incorporating a timer into a JavaScript game

I am currently working on a memory card game where I want to include a stopwatch feature. I'm looking to display the time elapsed from when the user selects the first card until they win. However, I am struggling with keeping the stopwatch running smo ...

Experiencing an issue with the countdown timer while utilizing react-countdown library

Currently, I am in the process of creating a countdown timer that allows users to input time in minutes and start or stop the clock. However, I have encountered two challenges: I defined a state running to determine if the clock is running, and based on t ...

The CSS background and background-image are visible exclusively on the Chrome desktop browser

Why is the background image not showing up on my website? The img src is also not displaying. All pictures show up fine on Chrome desktop browser, but not on Chrome mobile browser. Other browsers that are not displaying the images include Safari mobile, I ...

Using Jquery to Deactivate Field upon Meeting Conditions

In my form, there are 15 rows with unique IDs ranging from 1 to 15 (row_id). Each row consists of a select field and multiple text fields. My goal is to disable row_id 5 if the select option in rows 6 or higher is anything other than 0, and to disable row ...

JavaScript maintain a variable that holds onto nodes even after they have been removed

Recently, I encountered a seemingly simple issue with JavaScript that has me stumped. In my code, I have a variable that stores nodes with a specific class. My goal is to remove these nodes from the DOM while still retaining them in the variable. However, ...

Tips for expanding a script that relocates a logo into a navigation consisting of several unordered lists

I recently implemented a jQuery script to center a logo within my main navigation bar only when the screen width is above 980 pixels. It was working perfectly fine with a single unordered list, but as soon as I added more unordered lists within the nav, it ...

Error message: An uncaught promise was encountered, despite adding a catch function. I am unable to identify the issue causing this error

Why is the added catch block not functioning properly? function maxRequest(url = ``, times = 3) { // closure function autoRetry (url, times) { console.log('times = ', times); times--; return new Promise((resolve, reject) => ...

Navigating React Redux Pages Using React Router

At the moment, I am exploring the possibility of creating an application using React and Redux. Most examples I've come across make use of React Router, so I'm curious about its purpose. My application will consist of multiple pages (at least 20 ...

Send form using AJAX with a callback function

I need help figuring out how to submit a form when a captcha is clicked. I attempted to use my own jQuery function, but unfortunately it's not working. Could someone please take a look at my code and let me know what's wrong with it? Javascript ...

A guide on displaying JSON response data in Angular JS with the help of ng-repeat

I am attempting to display the values of a specific JSON in the correct order. Here is how my JSON is structured : { "A":[{"id":"21","name":"Andrea"},{"id":"22","name":"Apple"}], "B":[{"id":"21","name":"Baby"},{"id":"22","name":"Bali"}], "C":[{"id":"21"," ...

Creating fluid designs for my boxes with CSS to enhance responsiveness

I have designed my HTML file with 8 boxes that appear correctly on desktop, but when viewed on mobile devices, the columns are misaligned and shifted to the right side instead of being centered. How can I make it more responsive? See Preview Here is the ...

Activating text wrapping functionality

My current project involves converting HTML to PDF using jsPDF. In order to ensure that every word appears in the exact location as it does in the original HTML, I decided to wrap each word in <span> tags. Specifically, I have a font tag (not added b ...

Enabling or disabling select input based on the selected option in a previous select dropdown

My goal here is to customize a select input with 3 options: Sale, Rent, Wanted. Based on the selection, I want to display one of three other select inputs. For example, if "Sale" is chosen, show the property sale input and hide the others. However, when su ...

Incorporating Framer Motion into traditional React class components (non-functional approach)

I'm encountering an issue with a simple animation using Framer Motion that functions correctly in a functional component, but fails to work in a class component. I am new to Framer Motion and here is my react code => import {motion} from 'fr ...

Is there a way to command Chrome or Firefox to execute JavaScript or load a Bookmarklet directly from the command line?

Is there a way to execute javascript in the current browser window through the command line, either in Chrome or Firefox? Or is it possible to load a bookmarklet that includes javascript? I'm interested in creating a program that can monitor changes ...