disable image button if no image is selected in input field

Viewed 36

How can I disable the image button if no image is selected on the input field. The button should be disabled if the image not is 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;
1 Answers

I would just have a function that checks whether or not the input has a value inside of it and if not it leaves the button disabled. See snippet below. You can attach that logic to any event so if the input is blank the button will be set to disabled.

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>

Related