Send a textarea by pressing enter with JS?

Asked

Viewed 857 times

0

I’m having problems in my application because I have two types of textarea on the same page. One creates the post and the other creates the post comment.

The following code sends the post textarea:

document.onkeyup=function(e){
     if(e.which == 13){
        if(document.getElementById('textarea-post').value == ""){
        } else {
            document.enviaPost.submit();
        }
      }
 }

Code form above:

 <form action="posta.php" method="post" name="enviaPost">
    <ul class="form-post" >
       <li>
          <input type="hidden" name="data" value="<?= date("Y/m/d") ?>" />
          <textarea  placeholder="Como você está se sentindo?" name="contpost" id="textarea-post" /></textarea>
      </li>
          <input type="submit" value="Enviar" class="botao-enviar-post" />
  </ul>

What I would like to know is if, if I put another keyup like this pro comment textarea, it will cause some conflict. And if it does, I’d like to know how to do it without creating a conflict.

Second textarea:

<form  action="init/add_coment.php" method="post" name="enviaComent">
  <input type="hidden" value="<?=$post['id']?>" name="id_post" />
  <textarea id="texto_coment" name="comentario" class="comentario-texto" placeholder="Escreva um comentário..."></textarea> 
</form>

1 answer

1


Remember to add the Jquery library to your page

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>

This code will send the sending form

$('#textarea-post').keydown(function(event) {
        if (event.keyCode == 13) {
            this.form.submit();
        return false;
    }
});

Do the same thing on the send form

$('#texto_coment').keydown(function(event) {
        if (event.keyCode == 13) {
            this.form.submit();
        return false;
    }
});

https://jsfiddle.net/1h3dr7nt/

  • It didn’t work Lucas :/

  • Did you add jquery? Ideally it is at the bottom of the html code of the page, before closing the </body> so that the user does not have to wait for it to load to show the contents of the page and just below the jquery you will open <script> and put the 2 codes I posted and close </script>. open dev tools(Ctrl+shift+i) go to the Console tab and if you have an error post here

  • It worked! Thank you very much! I just moved the import to the bottom of the page and it worked out all right.

  • I had a problem here... On my page there is a form for each post. Thus, with the above script code, it only the first comment is working.. The others are not :/ How can I identify each textarea and each form?

  • Sorry for the delay, in all textarea you put the id="textarea-post" or id="texto_coment" will work with the above example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.