简体   繁体   中英

On Enter fire javascript function

After reading this post here in Stackoverflow, ( Detect the Enter key in an text input field ) I tried to make a few of my inputs fire on enter... I did not work. I made a simple example and it still doesn't work. Can someone hint as to the proper way? (FYI - Definitely a newbie here)

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>On Enter</title>

<script src="../../Scripts/jquery-2.1.0.min.js"></script> 
<script>
        $(".input1").keyup(function (e) {
            if (e.keyCode == 13) {
                alert ("It Works");
            }
        });
</script>

</head>

<body>


        <input type="text"
            id="input1"
            placeholder="Press Enter When Done">
        </input>


</body>
</html>

Thanks

First you need to say #input1 other than .input1 , then run it when the entire DOM is ready:

$(document).ready(function(){
    $("#input1").keyup(function (e) {
        if (e.keyCode == 13) {
            alert ("It Works");
        }
    });
});

Edit : As @jfriend00 mentioned in a comment it's a good idea to use e.which other than e.keycode . To do so you can change: e.keyCode == 13 to e.which == 13 . This way is recommenced by the people at jQuery, as it normalizes e.keyCode and e.charCode .

Change the .input1 in your JS to #input1

When you use . it means it's a class, but you have an ID, which is # .

Your code is triggering a "class", not an "id", so add a "#" instead of a "." in input1:

       $("#input1").keyup(function (e) {
            if (e.keyCode == 13) {
                alert ("It Works");
            }
        });

first, like the previous answer your criteria is not good. change for ID second, put your javascript at the and of the file on in the ready document. Because the javascript is in execution while the documenta as not finish to load . So the event can't be add to an element that doesnt exist.

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