Home > Mobile >  Disable submit button when Tags Input on textarea is empty
Disable submit button when Tags Input on textarea is empty

Time:01-09

I created a form where users can input words in a textarea as tags and submit them as a string using JavaScript. The feature I want to add is to disable the submit button whenever the textarea is empty (does not contain any tags).

Here is what I have tried so far:

HTML

<form>
  <textarea onkeyup="success()" name="tags" id="tag-input1" required>
  </textarea>
  <p >Press enter to add a new word</p>
  <!-- Disable Submit Button -->
  <input type="submit" id="submit"  value="Submit">
</form>

JavaScript

function success() {
  if (document.getElementById("tag-input1").value === "") {
    document.getElementById('submit').disabled = true;
  } else {
    document.getElementById('submit').disabled = false;
  }
}

DEMO

CodePudding user response:

I think you could check value length. At first, try to add disabled attribute to your submit button in html.

 <input type="submit" id="submit"  value="Submit" disabled="true">

Then in here is your success function code;

    function success() {
      document.getElementById('submit').disabled = !document.getElementById("tag-input1").value.length;
    }

CodePudding user response:

To disable the submit button when the tags input is empty, you can use the following approach:

  1. Add a disabled attribute to the submit button and set its value to true. This will disable the button initially.

    Submit

  2. Add an event listener to the textarea element that listens for the input event. This event is triggered whenever the value of the textarea changes.

    document.querySelector('textarea').addEventListener('input', function() { // Check if the tags input is empty });

  3. Inside the event listener, check if the value of the textarea is an empty string. If it is, disable the submit button by setting the disabled attribute to true. If the value is not empty, enable the submit button by setting the disabled attribute to false.

    document.querySelector('textarea').addEventListener('input', function() { // Check if the tags input is empty if (this.value === '') { document.querySelector('button').disabled = true; } else { document.querySelector('button').disabled = false; } });

This should disable the submit button when the tags input is empty and enable it when the input is not empty.

I hope this helps!

CodePudding user response:

As per my knowledge, that is not how disable works. Disable is a html attribute that stops user from writing data in the perticular text. Try providing error message when value of perticular message is empty You can use conditional statements for that

  • Related