Identify the right textarea to send when pressing Enter?

Asked

Viewed 178 times

1

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

The application loops posts recorded in the database and for each post has 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 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 press Enter send the comment in a specific textarea?

2 answers

2

I’d do it this way:

<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 his textarea it is not necessary to have an id, but a form will be required for each textarea, because you want to submit only the form who pressed Enter.

Inside the javascript you make the function:

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

The secret of this solution is to inform the id as argument of the javascript function, so you will have the necessary "clue" of which form to submit within the script.

An alternative to having several Forms on the same page would send by ajax, without using a form.Ubmit(), this would be useful if the post comment insertion landing page were the same page already with the new comment.

This second approach in addition to saving the refresh on the page demand less connection, and is more elegant because it does not scroll the page in the user’s browser.

1


The problem is that javascript is referencing the textarea #texto_coment, but in the 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 the class, so a javascript works for everyone.

Using the class:

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

Browser other questions tagged

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