0

hi2all i need to handle only the enter button event but my code handle enter even when i click

another button with it

for example when i click Shift+enter from kb it handle click i want to prevent such thing

i want to handle pressing enter alone

{____________ another issue i want to add new line after each appended text

my code is here

<!DOCTYPE HTML>
<html>

    <head>
        <meta http-equiv="content-type" content="text/html" />
        <meta name="author" content="gencyolcu" />
        <title>Untitled 1</title>
        <style>
</style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                $("#button1").click(function() {
                    $(this).attr("disabled", true);
                });
                $("#entr").keypress(function(e) {
                    if (e.which == 13) {
                        alert("enter pressed");
                        $("#texts").append($("#entr").val());
                    }
                });
            });
        </script>
    </head>

    <body>
        <div id="m" style="background-color: darkorange;">click me to change webpage background</div>
        <input id="entr" type="text" value="enter some text here" />
        <input id="button1" type="button" value="me" />
        <p id="texts">text in text box will appended here
            <br />
        </p>
    </body>

</html>
<script type="text/javascript">
    //change the color of webpage when clicking the div
    var x = document.getElementById("m");
    x.addEventListener("click", function() {
        document.body.style.backgroundColor = "darkturquoise";
    });
</script>
Smern
  • 18,746
  • 21
  • 72
  • 90
TheSniper104
  • 87
  • 1
  • 10

2 Answers2

0

Here's what you need to do. Bind your event keypress to the body.

jQuery(document).ready(function(){
    jQuery('body').on('keypress', function(e){
        //  We are looking for the action "enter"
        if(e.which == 13){
            //  Must not be with shift
            if(event.shiftKey !== true){
                alert(' Enter ! ');
            }
        }
    });
});

To add a new line, you have to append MyVar = MyVar + '<br />'+"\r\n";

David Bélanger
  • 7,400
  • 4
  • 37
  • 55
0

////will work for shift+enter if (event.keyCode == 13 && event.shiftKey) { } How do I detect "shift+enter" and generate a new line in Textarea?

Community
  • 1
  • 1
ram2013
  • 505
  • 2
  • 9
  • 19