0

I designed a form to send message with a submit button but for every message i have to use my cursor to click submit.How do i send message instead by hitting 'Enter" key of my keyboard. Here's my code

 <div class="message_post" id="myForm">
    <form action="" method="POST">

        <?php 
            if($user_to == "new") {

                echo "Send a message to your friend <br><br>"; ?>

                To: <input type='text' onkeyup='getUsers(this.value, "<?php echo $userLoggedIn; ?>")' name='q' placeholder='Search Username' autocomplete='off' id='search_text_input'>

                <?php
                echo "<div class='results'</div>";

            }
            else { // MESSAGE BOX

                if($userLoggedIn == $user_to)
                    echo "<p style='margin-left:275px;'>You can't send message to yourself</p>";
                else {

                echo "<textarea name='message_body' id='message_textarea' placeholder='Send a message'></textarea>";
                echo "<input type='submit' name='post_message' class='info' id='message_submit' value='Send'>";


                }


            }


         ?>


    </form>




 </div>

 <script>    // Javascript to automatically scrolling down to recent message

    var div = document.getElementById("scroll_messages");
    if(div != null) {
    div.scrollTop = div.scrollHeight;

    }
 </script>

chris85
  • 23,846
  • 7
  • 34
  • 51
Arno
  • 35
  • 1
  • 7
  • 5
    Possible duplicate of [Submitting a form on 'Enter' with jQuery?](https://stackoverflow.com/questions/699065/submitting-a-form-on-enter-with-jquery) – Qirel Jun 15 '17 at 15:50
  • PHP is not relevant for client side interactions. – chris85 Jun 15 '17 at 15:52
  • is this all of the relevant code? If you have an `` in a `form`, which you do, then hitting enter in the form will submit it. https://codepen.io/anon/pen/LLbxyd – Michael Coker Jun 15 '17 at 15:54
  • You're using a ` – rickdenhaan Jun 15 '17 at 15:55
  • Thanks man, it worked. But after messages are sent when i reload my page a pop-up asking for resubmission pops, if i press continue messages are repeated again. So for each reload my last message is repeated. So i added ' header("Location: messages.php");' under isset fucntion but that didn't work. – Arno Jun 16 '17 at 05:24

1 Answers1

0

This is the javascript code to listen the enter key and sumbit the form

$('html').keydown(function(e){
  if(e.which==13){
    document.getElementById("myForm").submit();
  }
});