简体   繁体   中英

PHP - HTML - Javascript - Submit text from textarea by pressing enter button

I'm making a simple chat using html-php-javascript. I wanna submit text from textarea to log file because "chatbox" will load the chats from there.

I wrote the code to submit text in textarea at "admin_post.php" and it works.

However, admin only can do that by pressing "send" button. Is it possible to make javascript so when admin pressing "enter" on the keyboard, it will do as same as pressing "send" button in form?

Here's the html code in admin_post.php:

<form id="admintextform" name="message" action="">
            <?php $adminmsg = !empty($_POST['adminmsg']) ? $_SESSION['adminmsg'] : '';?>
            <textarea class="admintextarea" name="adminmsg" id="adminmsg" size="63" /><?php echo $adminmsg; ?></textarea>
            <input name="adminsubmitmsg" type="submit"  id="adminsubmitmsg" value="Send" />
        </form>

and for the "send" button script:

<script type="text/javascript">
        //If user submits the form
        $("#adminsubmitmsg").click(function(){  
        var adminmsg = $("#adminmsg").val();
            $.post("admin_post.php", {text: adminmsg});             
            $("#adminmsg").attr("value", "");
            return false;
        });
</script>

I've tried this below script to solve my problem but it doesn't work. I hope the javascript below could do exactly same as the "send" button script above just by pressing enter button on the keyboard.

<script type="text/javascript">
        $("#admintextarea").keypress(function (e) {
            if(e.which == 13 && !e.shiftKey) {
                var adminmsg = $("#adminmsg").val();
                $.post("admin_post.php", {text: adminmsg});             
                $("#adminmsg").attr("value", "");
                return false;
            }
        });
</script>

Please help me and thanks for your time. :)

First, there was a problem with your HTML. you have closed the textarea tag on opening.

For the solution, I hope you find this JSFiddle helpful. Here's the code:

$("#adminmsg").on('keypress', function(e){
  if (e.which == 13)
  {
    e.preventDefault();
    console.log($(this).val());
    $(this).val("");
  }
});

Key points:

  1. You've got the selector wrong. the # corresponds to IDs, . corresponds to classes.
  2. Your code may be run before the document is fully loaded; hence it can't find an element to bind. Use on instead to do a binding to the corresponding selector anytime on the page; or use put your code inside $(document).ready(function(){ /* your code */ }); to be executed after the page is fully loaded and ready.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM