Inside Bootstrap modal windows I have this piece of html:
<form class="form-inline" role="form">
<button type="button" class="btn btn-training-comment btn-lg">
<a href="#"> <img src="/img/training-icon-large.png" alt="icon" width="35" height="24"></a>
</button>
<div class="form-group training-comment-form-wrapper">
<label class="sr-only" for="commentInput">Enter comment..</label>
<input type="text" class="form-control training-comment" id="commentInput" placeholder="Enter comment">
</div>
</form>
And I have this Javascript code:
$("#commentInput").onkeypress = function (e) {
if (!e) e = window.event;
var keyCode = e.keyCode || e.which;
if (keyCode == '13') {
console.log("clicked");
addComment();
}
};
But my enter key press isn't captured and "clicked" never gets logged. Why is this happening ?
Use
$("#commentInput").keypress(function (e) {
instead
$("#commentInput").onkeypress = function (e) {
The quotes in
if (keyCode == '13') {
are not necessary.
I updated your onkeypress to use .on() and removed some other unnecessary things. You were also comparing a number to a string. keyCode == '13' . Hope this helps.
$(document).ready(function(){
$(document).on('keypress','#commentInput', function (e) {
console.log('Keyboard Key Number: '+e.which);
if (e.which == 13) {
e.preventDefault();
console.log('enter was pressed. ');
}
});
});
Also, you should remove the anchor tag nested within the . There is no need for that.
<button type="button" class="btn btn-training-comment btn-lg">
<a href="#"> <img src="/img/training-icon-large.png" alt="icon" width="35" height="24"></a>
</button>
Here is a working fiddle : http://jsfiddle.net/FVK7f/ - (Using your markup) with an additional wrapping div around the form.
Edit: changed event binding to use document.
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.