0

Dont looking for Jquery solution

The suggested link dont helps me. But I found this answer (https://stackoverflow.com/a/39270603/18066399) which helps me

Thx!

I have a form with a textarea and a button. The textarea has the attribute required and the button is bound to a click event. The event then triggers a process. a) get the data from the textarea and b) send (POST) it against the API.

My two problems

  1. required works like this. But the data is then sent from the form and a 500 error occurs.
  2. if I then add an event.preventDefault() to the callback of the event listener, the api request works correctly but with an empty field the form attribute required does not work.

What I have tried I added method and action to the form. This would then work but the page is reloaded (which I don't want). As you can see in my example below that if you leave the textfield empty the required attribute dont work. I expect to see the default note: Please fill out the field. If i will remove the preventDefault option then the form will show the hint.

Question How can I use the required attribute together with a click event listener?

My code

const submitComment = document.querySelector('#submitComment');
submitComment.addEventListener('click', async (ev) => {
  ev.preventDefault();
  const textarea = document.querySelector('textarea[name="comment-content"]');
  const comment = textarea.value;
  const id = textarea.getAttribute('data-item-id');
  
  if (comment.length === 0) return false;
  const res = await send('POST', '/v1/api/comments/post', {
    content: comment,
    id: id
  });
  console.log(res)
  return false;
});

function send(m,u,d) {
  return true;
}
<form class="createComment">
  <label for="comment">Your Comment</label>
  <textarea
            required
            id="comment"
            type="text"
            placeholder="Comment"
            name="comment-content"
            class="comment__textarea"
            data-item-id="1"></textarea>
  <button id="submitComment">Post Comment</button>
</form>
Max Pattern
  • 1,430
  • 7
  • 18
  • The related answer is false! Please replace with this link: https://stackoverflow.com/a/39270603/18066399. This answer was helpful for me. – Max Pattern Jan 19 '23 at 10:05

0 Answers0