Identify the correct textarea to send by pressing Enter?

1

I had "solved" a problem sending a textarea by pressing Enter in my application, but it ended up only sending it to the first textarea of the page.

The application loops registered posts in the database and for each post there is an area for the user to comment on. The following code sends the contents of the first textarea by pressing enter:

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

What happens is that on the page there are more than one post and I do not know how to identify each one of them.

Comment Form:

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

How can I do to press Enter to comment on a specific textarea?

    
asked by anonymous 26.02.2017 / 18:10

2 answers

1

The problem is that javascript is referencing the textarea #texto_coment , but in textarea the id is another texto_coment_<?=$post['id']?>

The solution is to make javascript reference the textarea correctly, as you have more than one textarea it is interesting to do this by class, so one javascript works for everyone.

Using the class:

$('.comentario-texto').keydown(function(event) {
    if (event.keyCode == 13) {
        this.form.submit();
        return false;
     }
});
    
26.02.2017 / 22:02
2

I would do it as follows:

<form  action="init/add_coment.php" method="post" id="enviaComent<?=$post['id']?>">
<textarea  name="comentario" class="comentario-texto" placeholder="Escreva um comentário..." onkeypress="javascript:submeterTextArea(event.keyCode,<?=$post['id']?>);"></textarea>

In your textArea it is not necessary to have an id, but you will need a form for each textArea , since you want to submit only the form that you pressed Enter .

Within the javascript you do the function:

function submeterTextArea(ev,id){
    if(ev==13){
       $('#enviaComent'+id).submit();
    }
}

The secret of this solution is to inform the id as the javascript function's argument, so you'll have the necessary "clue" to submit within .

An alternative to having multiple forms on the same page would be sending ajax , without using a form.submit () , this it would be useful if the landing page after posting the comment was the same page already with the new comment.

This second approach aside from saving refresh on the page requires less connection, and is smarter as it does not scroll the page in the user's browser.

    
26.02.2017 / 22:33