Deactivate the image button when no image has been chosen from the input field

Is it possible to have the image button disabled when no image is selected in the input field? The button should be inactive if an image is not chosen.

import { useState } from "react";

const CommentForm = ({ handleSubmit, submitLabel }) => {
  const [text, setText] = useState("");
  const textType = "plainText";
  const textDisabled = text.length === 0 || text.trim().length === 0;
  const onSubmit = (event) => {
    event.preventDefault();
    handleSubmit(text, null, textType);
    setText("");
  };

  return (
    <form onSubmit={onSubmit}>
      <textarea
        className="comment-form-textarea"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
      <button className="comment-form-button" disabled={textDisabled}>
        {submitLabel}
      </button>
    </form>
  );
};

export default CommentForm;

Answer №1

To ensure the button remains disabled when the input is empty, a simple function can be implemented to check for any value within the input. By attaching this logic to an event handler, such as keyup, the button will automatically disable or enable based on the user's input. See the code snippet below for an example:

const imageFile = document.getElementById('imageFile');
const submitImage = document.getElementById('submitImage');

imageFile.addEventListener('keyup', function(){
if(imageFile.value !== "") {
  submitImage.removeAttribute('disabled');
  } else if(imageFile.value === "") {
  submitImage.setAttribute('disabled', true);
  }
});
<input id="imageFile" type="text" placeholder="Enter text here" />
<button id="submitImage" disabled>Submit Image</button>

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

Tips for utilizing @htmlattributes when configuring a datepicker:

Hello, I am attempting to change a simple input field into a date form. I have tried using the DateTime property with @Html.TextBoxFor(model => model.dateFin, new { type = "date" }) but it was not successful. As a result, I am resorting to using a simpl ...

Finding the current week using date information from an array of objects in JavaScript

I have an array of objects with a date key, and I am trying to filter out the objects that fall within the current week. How can I achieve this and get the objects from the current week? I attempted to use the filter method, but I believe I need to forma ...

A unique way to present data: An HTML table featuring four fixed columns with horizontal scrolling

I've been having difficulty creating a table with fixed first four columns while allowing the rest to scroll horizontally. I came across this example first column fixed Although the example has the first column fixed, I'm struggling to extend it ...

React-select is failing to show the input field when changing the value prop with state hooks

I have been attempting to create a dynamic input field in React using react-select. The input field should display more options when the user interacts with it. I noticed that the input field displays properly when I do not modify the value prop using stat ...

Authenticating Users in Django with ReactJS Themes

Currently, my login template is being served by Django templates without any React components. However, I have integrated ReactJS and created routes, components, and pages that are fully based on React. Now, I am figuring out a way to allow users to log in ...

Jest: A runtime error occurred because the property being accessed is undefined

Currently, I am testing my React class which includes the import statement import dotnetify from "dotnetify";. While this works without any issues, Jest is reporting that dotnetify is undefined. Interestingly, when I switch the import to const do ...

What could be the reason behind the "Package.json has missing dependencies" error message in create-react-app?

What's the issue: Recently, I began learning reactjs. In the process of creating a new react app, the build fails and only a package.json file is generated. > PS D:\react-projects> npx create-react-app app-name Creating a new > Reac ...

My program is able to perform calculations even in the absence of user input

I have been encountering an issue with my PHP code that is used for performing calculations. The code is designed to take inputs from textboxes and calculate the total based on those values. However, when I click the button intended for calculating the tot ...

Could the addition of iframes enhance the efficiency of websites containing a vast amount of DOM elements?

When dealing with websites that have a massive amount of DOM elements, could there be any performance advantages to displaying some content within an iframe? For instance, the project I am currently involved in features a large HTML-based tree structure ...

Is it possible to increase the delay in the nth-child selector?

I'm attempting to create a compact checklist that displays in a single row with items appearing sequentially. To achieve this, I utilized the :nth-child() selector in CSS as shown below: .animated { -webkit-animation-duration: 0.8s; animation-d ...

The drag functionality can only be used once when applied to two separate div elements

Recently, I came across an issue where I have both an Image and a custom text element placed between them using an input box. My goal is to make both the text and the image draggable on the page. However, I noticed that while the image can be dragged and d ...

What could be the reason for my post container not functioning properly?

I am facing an issue with my HTML and CSS code. The container is not displaying as expected, specifically the green bar that should appear below the image. I suspect that the container's auto attribute is causing it to overlook the content inside. Can ...

Troubleshooting a CSS problem within mat-autocomplete component in Angular 7

While using mat-autocomplete, I noticed that when I select an option from the dropdown and then scroll through the main bar, the dropdown menu does not move along with the autocomplete input field. view image here Here is the code snippet: <td width ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

I am experiencing an issue with applying responsiveFontSize() to the new variants in Material UI Typography

I am looking to enhance the subtitles in MUI Typography by adding new variants using Typescript, as outlined in the documentation here. I have defined these new variants in a file named global.d.ts, alongside other customizations: // global.d.ts import * a ...

Employ the CSS pseudo-element :before within a UL element to generate a vertical line

I'm currently working on a vertical menu with the capability of having submenus. My aim is to include a vertical line using CSS pseudo-element ::before along with border. The challenge I'm encountering is that the CSS is applying to the entire m ...

Tips for generating documentation using markdown within the docs directory on GitHub with the help of JavaScript

After browsing through numerous documentation websites, I have noticed that many of them share the same layout and features. This has led me to question whether there is a common library used by all these documentation sites. How do they achieve this unif ...

Issue with the text wrapping of Angular mat-list-option items

When the text of my checkboxes is too long, it doesn't wrap properly. Please see the image below for reference: Click here to view Checkbox image and check the red box Here is my HTML code: <mat-selection-list #rolesSelection ...

Utilizing CSS classes and IDs for unordered lists

What's the correct way to write it when the ul is a class instead of an id? ul#Menu li a{} ul.Menu li a{} isn't functioning correctly ...

Tips for Providing a Generic Type to a Component Imported Using Next.js Dynamic

There is no issue with this code snippet: import DatasheetContainer from '@/uikit/detailed-view/DatasheetContainer'; const DetailedView = () => { return ( <Page> <PageBody direction="row" bgColor="white&qu ...