0

I need to connect a button with a textarea though they are not connected in a form.

My requirement? I need the button when clicked to check if the textarea is empty using the default required tag.

If clicking the button, and the textarea is empty, it needs to show the default error generated by the browser. I think Chrome etc says something like "This field is required".

Just connecting them in a form would make it easy, but it is not possible to connect them in a form-tag.

Makes sense? Maybe using JS?

Thanks!

  • https://stackoverflow.com/questions/7002230/trigger-standard-html5-validation-form-without-using-submit-button – epascarello Jun 01 '21 at 12:23
  • or without JS https://stackoverflow.com/questions/7020659/submit-form-using-a-button-outside-the-form-tag/12567605#12567605 – epascarello Jun 01 '21 at 12:24

1 Answers1

0

Here is the most basic example (logic only)

document.getElementById('my-btn').addEventListener('click', function(){
      let taVal = document.getElementById('my-textarea').value;
      if(taVal == ''){
        alert('This field is required')
      } else{
        console.log("success")
      }
    }

Without JS, you can just add required to the tag like

<textarea required></textarea>

Here is the fully working example without JavaScript

<form>
  <textarea placeholder="Enter your text here..." required></textarea>
  <button type="submit" id="my-btn">Submit</button>
</form>
Aspect
  • 150
  • 11