I am trying to disable a textarea from handling a keyboard event when ever a user presses the enter key of the keyboard when the textarea is empty using angularjs. I have been able to disable the submit button when the textarea is empty but I am trying to disable the textarea when from enter event when the textarea is empty.
This is my attempt:
<div class="descriptionarea">
<textarea ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div>
When I hit enter from my textarea it triggers event using the following code
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { // enter key press
send();
}
});
The above code works whether the textarea is empty or not.
EDITTED:
In my app.js of angularjs
app.controller('TodoCtrl',function($scope){
//handle javascript enter event on key up
// function TodoCtrl($scope) {
$scope.trackTxt;
$scope.send = function($event){
alert('TEST');
}
$scope.isEmpty = function(param){
return param.trim().length === 0;
}
//}
});
In jsp file
<div ng-controller="TodoCtrl">
<textarea ng-keyup="$event.keyCode == 13 && !isEmpty(trackTxt) && send($event)" ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" ng-click="send($event)" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div></div>
Please how can I use angularjs to prevent the enter event from happening when ever the text-area is empty.
You can use ng-keyup for attaching an function on enter key press,
ng-keyup="$event.keyCode == 13 && functionToCall()"
Here is demo,
Thanks
You could simply check if it's empty...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val() != "") { // enter key press
send();
}
});
This also may work:
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
send();
}
});
To prevent the default enter use preventDefault() Event Method
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
});
How about the sendChat()...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
else if(code == 13 && $(this).val().length > 0) {
sendChat();
}
});
Related
when i press enter key on txtZip textbox It MOve to other page rather then calling JS i wanna set another text box value eqaul to txtZip
<asp:TextBox Style="text-align: center" ID="Txt_Zip" runat="server" Width="120px"
Text="Zip" onkeypress="return runScript(event)"></asp:TextBox>
<asp:TextBox Style="text-align: center" ID="Txt_Second" runat="server" Width="120px"
Text="Zip"></asp:TextBox>
function runScript(e)
{
if (e.which == 13 || e.keyCode == 13)
{
var zip =document.getElementById("txtZip").value;
document.getElementById("txt_Second").value=zip;
}
}
as i ahve one button also that re direct to another page on click how to restrict that on pressing enter key on text box just call JS ??
Hopes for your suggestions
Thanks
try this:
<script>
$(document).ready(function() {
$("input[id$='Txt_Zip']").on('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
$("input[id$='Txt_Second').val($(this).val());
return false;
}
});
});
</script>
Try this:
function runScript(e)
{
if (e.which == 13 || e.keyCode == 13)
{
var zip =document.getElementById("txtZip").value;
document.getElementById("txt_Second").value=zip;
return false;
}
}
Just add e.preventDefault(); inside the if statement braces. This tells the event to not carry out the default action (submitting the form).
function runScript(e)
{
if (e.which == 13 || e.keyCode == 13)
{
var zip =document.getElementById("txtZip").value;
document.getElementById("txt_Second").value=zip;
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
}
I'm trying to implement a form with multiple buttons on it. When I press enter I want to have my default button submitted. This code from http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/ generally works:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
});
but...
when I type in input field I have an autocomplete popup so when I press enter in this popup I expect to put this value to input field, not submit all form. Can I check somehow if this enter comes from popup? Or I should try to do this different way?
EDIT:
I think I didn't say it clear. This popup is not any part of jquery. It's standard popup that shows previously typed data into input. So it hasn't got any class nor id. Stop propagation doesn't work either. None of solutions below resolve this problem
You could use :visible to see if the dropdown div for the autocomplete is open, and then prevent the enter key action of your code completing. Something like this:
$("form input").keypress(function(e) {
var key = e.which || e.keyCode;
if (key == 13 && !$(".autocomplete").is(":visible")) {
e.preventDefault();
$('form').submit();
}
});
You could also use event.stopPropagation() on the enter key press in the autocomplete function, however you'll probably have to amend the source manually which isn't ideal.
Before return false;
write
e.preventDefault();
or/and
e.stopPropagation();
$("form input").keypress(function (e) {
if (e.target.id !== "autoCompliteId" && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
I modified my code and it works now.
I have an enum called Operation in my command and I set different value of the field before every submit button eg:
<input type="submit" value="do sth" onclick="setOperationAndSubmit('DO_STH')"/>
<input type="submit" value="next" onclick="setOperationAndSubmit('DEFAULT')"/>
function setOperationAndSubmit(operation) {
if (document.myForm.elements['operation'].value === '') {
document.myForm.elements['operation'].value = operation;
}
document.myForm.submit();
}
Then I have my action that listens to keypress and it set appropriate operation on every enter key:
$(function() {
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.myForm.elements['operation'].value = 'DEFAULT';
}
});
});
so default action is executed when I press enter
How to do that?
I tried:
var key = event.which || event.keyCode || event.charCode;
if(key == 8) alert('backspace');
but it doesn't work...
If I do the same on the keypress event it works, but I don't want to use keypress because it outputs the typed character in my input field. I need to be able to control that
my code:
$('#content').bind('input', function(event){
var text = $(this).val(),
key = event.which || event.keyCode || event.charCode;
if(key == 8){
// here I want to ignore backspace and del
}
// here I'm doing my stuff
var new_text = 'bla bla'+text;
$(this).val(new_text);
});
no character should be appended in my input, besides what I'm adding with val()
actually the input from the user should be completely ignored, only the key pressing action is important to me
Use .onkeydown and cancel the removing with return false;. Like this:
var input = document.getElementById('myInput');
input.onkeydown = function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
};
Or with jQuery, because you added a jQuery tag to your question:
jQuery(function($) {
var input = $('#myInput');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if( key == 8 || key == 46 )
return false;
});
});
event.key === "Backspace"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Mozilla Docs
Supported Browsers
With jQuery
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
http://api.jquery.com/event.which/
jQuery('#input').on('keydown', function(e) {
if( e.which == 8 || e.which == 46 ) return false;
});
It's an old question, but if you wanted to catch a backspace event on input, and not keydown, keypress, or keyup—as I've noticed any one of these break certain functions I've written and cause awkward delays with automated text formatting—you can catch a backspace using inputType:
document.getElementsByTagName('input')[0].addEventListener('input', function(e) {
if (e.inputType == "deleteContentBackward") {
// your code here
}
});
keydown with event.key === "Backspace" or "Delete"
More recent and much cleaner: use event.key. No more arbitrary number codes!
input.addEventListener('keydown', function(event) {
const key = event.key; // const {key} = event; ES6+
if (key === "Backspace" || key === "Delete") {
return false;
}
});
Modern style:
input.addEventListener('keydown', ({key}) => {
if (["Backspace", "Delete"].includes(key)) {
return false
}
})
Mozilla Docs
Supported Browsers
Have you tried using 'onkeydown'?
This is the event you are looking for.
It operates before the input is inserted and allows you to cancel char input.
$('div[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13 || e.keyCode === 8)
{
return false;
}
});
InputEvent.inputType can be used for Backspace detection Mozilla Docs.
It works on Chrome desktop, Chrome Android and Safari iOS.
<input type="text" id="test" />
<script>
document.getElementById("test").addEventListener('input', (event) => {
console.log(event.inputType);
// Typing of any character event.inputType = 'insertText'
// Backspace button event.inputType = 'deleteContentBackward'
// Delete button event.inputType = 'deleteContentForward'
})
</script>
on android devices using chrome we can't detect a backspace.
You can use workaround for it:
var oldInput = '',
newInput = '';
$("#ID").keyup(function () {
newInput = $('#ID').val();
if(newInput.length < oldInput.length){
//backspace pressed
}
oldInput = newInput;
})
//Here's one example, not sure what your application is but here is a relevant and likely application
function addDashesOnKeyUp()
{
var tb = document.getElementById("tb1");
var key = event.which || event.keyCode || event.charCode;
if((tb.value.length ==3 || tb.value.length ==7 )&& (key !=8) )
{
tb.value += "-"
}
}
Live demo
Javascript
<br>
<input id="input">
<br>
or
<br>
jquery
<br>
<input id="inpu">
<script type="text/javascript">
var myinput = document.getElementById('input');
input.onkeydown = function() {
if (event.keyCode == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.keyCode == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
};
//jquery code
$('#inpu').on('keydown', function(e) {
if (event.which == 8) {
alert('you pressed backspace');
//event.preventDefault(); remove // to prevent backspace
}
if (event.which == 46) {
alert('you pressed delete');
//event.preventDefault(); remove // to prevent delete
}
});
</script>
This is what I want to happen.. When a user hits 'enter' a 'SearchForItems()' should trigger. What is happening is another control, with 'other button', on the page gets focus returned to it anytime any other element is tabbed out of or after onkeyup.
I am having to force focus on the 'Search button' on page load, but after that any time enter is pressed the 'other button' is triggered. The 'other button' does not have a tab index assigned and is the pages default button.
I'm not sure if I've done a good job explaining this. Basically I want to know why focus is being shifted and how I can force the 'Search button' to trigger anytime enter is pressed.
this is one entry on my page where I'm trying to force the 'Search button' to trigger:
<td><input type="text" onkeydown="CheckForEnterKey(event)" id="AcceptedDate1" maxlength="7" style="width:121px;" value="<%=DateTime.Now.AddMonths(-3).ToString("MM/yyyy")%>"/> </td>
this is part of my jquery file where i'm also
$('#AcceptedDate1').keypress(function(e) { if (e.keyCode == 13 || e.which == 13) $('#SearchAcceptedLotsButton').click(); });
CheckForEnterKey Function
function CheckForEnterKey(e)
{
var keycode;
if(e.which)
{
keycode = e.which;
}
else
{
keycode = e.keyCode;
}
if(keycode == 13)
{
$('#SearchAcceptedLotsButton').click();//tried SearchForItems() also
}
}
Edit:
I just added this to my page and it appears to work, I added this to the main div thats holding everything together. What I need to do now is figure out where the enter was pressed so the enter is canceled everytime it is pressed within the main portion of my page. Any ideas, there are a lot of elements on my page?
function checkKey(e)
{
if(e.keyCode == 13 || e.which == 13)
{
e.returnValue = false;
e.cancel = true;
}
}
I am not sure why you are having problems. But I can offer you my onKeyDown code for pressing enter:
if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) { #DO JS HERE # }}
So I use it like this:
<input type="text" onKeyDown="if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) { alert('You pressed enter!'); }}">
In the above code whenever enter is pressed the id="SearchAcceptedLotsButton" can be triggered click as follows :
if(keycode == 13)
{
$('#SearchAcceptedLotsButton').trigger('click');
}
this is how I resolved the issue:
I added this function..
function checkKey(e)
{
if(e.keyCode == 13 || e.which == 13)
{
e.returnValue = false;
e.cancel = true;
SearchAcceptedLots();
}
}
At the top most div containing everything on the page I added this:
<div id="ItemPanel" onkeydown="checkKey(event)">
this catches every enter that is pressed within the form, canceling the default buttons behavior and calling the desired function.
I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
It looks like I need to use the keypress() method.
Are there browser issues with that command - like are there any browser compatibility issues I should know about?
The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:
$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
I wrote a small plugin to make it easier to bind the "on enter key pressed" event:
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if (keycode == '13') {
fnc.call(this, ev);
}
})
})
}
Usage:
$("#input").enterKey(function () {
alert('Enter!');
})
I couldn't get the code posted by Paolo Bergantino to work, but when I changed it to $(document) and e.which instead of e.keyCode then I found it to work faultlessly.
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed Enter!');
}
});
Link to example on JS Bin
I found this to be more cross-browser compatible:
$(document).keypress(function(event) {
var keycode = event.keyCode || event.which;
if(keycode == '13') {
alert('You pressed a "enter" key in somewhere');
}
});
You can do this using the jQuery 'keydown' event handler:
$("#start").on("keydown", function(event) {
if(event.which == 13)
alert("Entered!");
});
Use event.key and modern JavaScript!
$(document).keypress(function(event) {
if (event.key === "Enter") {
// Do something
}
});
Or without jQuery:
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
// Do something better
}
});
Mozilla documentation
Supported Browsers
I came up with this solution:
$(document).ready(function(){
$('#loginforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('login pressed');
}
});
$('#signupforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('register');
}
});
});
There's a keypress() event method. The Enter key's ASCII number is 13 and is not dependent on which browser is being used.
A minor extension of Andrea's answer makes the helper method more useful when you may also want to capture modified enter presses (i.e., Ctrl + Enter or Shift + Enter). For example, this variant allows binding like:
$('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
to submit a form when the user presses Ctrl + Enter with focus on that form's textarea.
$.fn.enterKey = function (fnc, mod) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = (ev.keyCode ? ev.keyCode : ev.which);
if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
fnc.call(this, ev);
}
})
})
}
(See also *Ctrl + Enter using jQuery in a TEXTAREA)
In some cases, you may need to suppress the ENTER key for a certain area of a page but not for other areas of a page, like the page below that contains a header <div> with a SEARCH field.
It took me a bit to figure out how to do this, and I am posting this simple yet complete example up here for the community.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test Script</title>
<script src="/lib/js/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('.container .content input').keypress(function (event) {
if (event.keyCode == 10 || event.keyCode == 13) {
alert('Form Submission needs to occur using the Submit button.');
event.preventDefault();
}
});
</script>
</head>
<body>
<div class="container">
<div class="header">
<div class="FileSearch">
<!-- Other HTML here -->
</div>
</div>
<div class="content">
<form id="testInput" action="#" method="post">
<input type="text" name="text1" />
<input type="text" name="text2" />
<input type="text" name="text3" />
<input type="submit" name="Submit" value="Submit" />
</form>
</div>
</div>
</body>
</html>
Link to JSFiddle Playground: The [Submit] button does not do anything, but pressing ENTER from one of the Text Box controls will not submit the form.
Try this to detect the Enter key pressed.
$(document).on("keypress", function(e){
if(e.which == 13){
alert("You've pressed the enter key!");
}
});
See demo # detect enter key press on keyboard
As the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
$(document).keydown(function(event) {
if (event.keyCode || event.which === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Call function, trigger events and everything you want to do. Example: Trigger the button element with a click
$("#btn").trigger('click');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')"> </button>
I used $(document).on("keydown").
On some browsers keyCode is not supported. The same with which so if keyCode is not supported you need to use which and vice versa.
$(document).on("keydown", function(e) {
const ENTER_KEY_CODE = 13;
const ENTER_KEY = "Enter";
var code = e.keyCode || e.which
var key = e.key
if (code == ENTER_KEY_CODE || key == ENTER_KEY) {
console.log("Enter key pressed")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
$(document).keydown(function (event) {
//proper indentiation of keycode and which to be equal to 13.
if ( (event.keyCode || event.which) === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btnsearch").trigger('click');
}
});
This my how I solved it. You should use return false;
$(document).on('keypress', function(e) {
if(e.which == 13) {
$('#sub_btn').trigger('click');
alert('You pressed the "Enter" key somewhere');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sub_email_form">
<div class="modal-header">
<button type="button" class="close" id="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Subscribe to our Technical Analysis</h4>
</div>
<div class="modal-body">
<p>Signup for our regular Technical Analysis updates to review recommendations delivered directly in your inbox.</p>
<div class="input-group">
<input type="email" name="sub_email" id="sub_email" class="form-control" placeholder="Enter your email" required>
</div>
<span id="save-error"></span>
</div>
<div class="modal-footer">
<div class="input-group-append">
<input type="submit" class="btn btn-primary sub_btn" id="sub_btn" name="sub_btn" value="Subscribe">
</div>
</div>
</form>
I think the simplest method would be using vanilla JavaScript:
document.onkeyup = function(event) {
if (event.key === 13){
alert("Enter was pressed");
}
}
The easy way to detect whether the user has pressed Enter is to use the key number. The Enter key number is equal to 13.
To check the value of key in your device:
$("input").keypress(function (e) {
if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25)
|| (97 <= e.which && e.which <= 97 + 25)) {
var c = String.fromCharCode(e.which);
$("p").append($("<span/>"))
.children(":last")
.append(document.createTextNode(c));
} else if (e.which == 8) {
// Backspace in Internet Explorer only is on keydown
$("p").children(":last").remove();
}
$("div").text(e.which);
});
By pressing the Enter key, you will get result as 13. Using the key value, you can call a function or do whatever you wish:
$(document).keypress(function(e) {
if(e.which == 13) {
console.log("The user pressed the Enter key");
// The code you want to run
}
});
If you want to target a button once the Enter key is pressed, you can use the code:
$(document).bind('keypress', function(e) {
if(e.which === 13) { // Return
$('#buttonname').trigger('click');
}
});
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
$(function(){
$('.modal-content').keypress(function(e){
debugger
var id = this.children[2].children[0].id;
if(e.which == 13) {
e.preventDefault();
$("#"+id).click();
}
})
});