Reputation: 514
I'm using some jQuery to link the Enter key to an HTML button using the following code:
$("#console").keyup(function(event){
if(event.keyCode == 13) {
$("#submit").click();
}
});
HTML:
<input autocomplete="off" type="text" id="console" placeholder="/help, /attack, /heal, /flee" autofocus></input>
<input type="submit" onclick="play()" id="submit" value="Enter"></input>
For some reason, it's not working for me right now. There's no error message, it seems like the jQuery doesn't even run.
What am I doing wrong? Do I have to replace event
with something?
Upvotes: 0
Views: 5281
Reputation: 1
$("#console").keyup(function(event){
if(event.keyCode == 13) {
$("#submit").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="console"autofocus></input>
<input type="button" onclick="alert('hurray')" value="enter" id="submit"></input>
Upvotes: 0
Reputation: 1
$("#console").keyup(function(event){
if(event.keyCode == 13) {
$("#submit").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="console"autofocus></input>
<input type="button" onclick="alert('hurray')" value="enter" id="submit"></input>
Upvotes: 0
Reputation: 514
Err... a beginner's mistake...
I forgot to use:
$(document).ready(function() {
});
Nothing provoked the code to run in the first place so it never worked. Noticed it in Teemu's fiddle.
Upvotes: 0
Reputation: 3305
'#' means id, here is reference http://api.jquery.com/category/selectors/ and http://api.jquery.com/id-selector/
if you want to use id, try this, http://api.jquery.com/multiple-attribute-selector/
$("#submit").click();
if you want to use value='Enter', try this,
$("input[value='Enter']").click();
Try this JS code. Also you can find demo in FIDDLE as well.
$("#submit").click(function(){
alert('Enter clicked!');
});
$("#console").keyup(function(event){
if(event.keyCode == 13) {
$("#submit").click();
}
});
Upvotes: 0
Reputation: 58455
$("#enter").click();
selects elements with the id
"enter". It seems you're hoping to select your submit button but it has the id submit
so try using $("#submit").click();
$("#console").keyup(function(event){
if(event.keyCode == 13) {
$("#submit").click();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="console"autofocus></input>
<input type="button" onclick="alert('hurray')" value="enter" id="submit"></input>
See: http://api.jquery.com/category/selectors/ and I also just discovered this which looks pretty helpful: http://learn.jquery.com/using-jquery-core/selecting-elements/
Upvotes: 0