I thought I'd handle not clicking on my default button (which is on my asp.net master page) by checking if enter was pressed and handling it. Basically when users were on any input type fields and they hit enter, it would actually execute the event of my default button on my form (as mentioned it is a button on my master page that allows for a global search).
So users were like hey wait a minute i hit the enter key on an input field why am I suddenly on a search results page....I dont blame them...
I thought I'd handle it with this:
$(document).keypress(function (e) {
if (e.which == 13) {
return false;
}
});
Which the problem no longer happened, and I was happy...until I found out all my buttons on for instance my jquery dialog no longer executed when you tabbed to them and hit the enter key...Well I see the reason why because I'm returning false. But how should I structure this so this does not happen if you are focused in on a for example asp.net button?
You should only on handle textboxes
$('input[type=text]').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
EDIT
As per comment, Can I add this in my site.master page but ignore one specific text box
Excluding a textfield
$('input[type=text]').not('.search').keypress(function (e) {
if (e.which == 13) {
return false;
}
});
Here I have include a demonstration, In last textbox (search) event is not associated.
Use Event Delegation Approach
$(document).on('keypress', 'input[type=text]:not(.search)', function (e) {
if (e.which == 13) {
alert('Enter pressed')
}
});
DEMO
You need to bind even to exact element on page:
$('.aspNetButton').on('keypress', (function (e) {
if (e.which == 13) {
return false;
}
});
Related
What may be the reason, that event listener of Enter key doesn't work?
I tried both plain JS:
addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
enter(e);
}
});
function enter(e) {
event.preventDefault();
alert("You pressed enter");
}
and jQuery:
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
Also, I tried both event and e. Doesn't work. For another key, for example Backspace it works well.
That is a plugin for our corporate intranet - when you click some letter in email inbox, and after that press Enter, small pop-up window must be shown. But for some reason Enter is ignored in my script - instead of showing pop-up, webpage immediately opens the letter (that is a default behavior).
As I understand, the reason may be in another listener somewhere in webmail interface? Or not? If yes, may I somehow impart higher priority for handling Enter (so, before opening the letter, pop-up will be shown)?
Apologize for long description.
It should work as long as you bind the event handler within the document.ready
$(function(){
$(document).keypress(function(e) {
if(event.which == 13) {
event.preventDefault();
alert('You pressed enter!');
}
});
});
Here is a working sample
I would like to trigger a click if enter is pressed inside an input tag, but would like to have the default event strategy in all other cases. I have tried it this way:
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
It works, but I am still not satisfied, because when I click inside the input somewhere in the middle of text or press the left button, or home button and then try to type some text, it will show it at the end of the input, which is bad user-experience. Can I keep the input to work in the default way except the case when enter is pressed?
I think what you are looking for is this:
$(document).ready(function () {
$("#test").keyup(function (event) {
if (event.keyCode == 13) {
$("#campus-search").click();
}
});
$("#campus-search").click(function () {
console.log("BUTTON IS CLICKED");
});
});
The input will act completely normal and everything works on default, unless when you press the enter button (keyCode = 13), then the button .click() event will be triggered.
Working Fiddle: http://jsfiddle.net/Mz2g8/3/
————
# Update: Just one hint for the code in your question, do not use charCode, as it is deprecated.
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.
(E.g. charCode does not work with FF v29.0.1)
And something different but important to know:
charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.
Source: https://developer.mozilla.org/en-US/docs/Web/API/event.charCode
This should work
$("#keywords").keypress(function(e) {
if (e.charCode === 13) {
e.preventDefault(); // prevent default action of the event if the event is keypress of enter key
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
I think you can eliminate the else clause entirely to get your desired result.
Look at this jsfiddle.
The keypress function does not capture non-printing keys, such as shift, esc, delete, and enter, so the best way to go about this would be have two event handlers: one for keypress, as you have defined above, and one for keydown that checks for the charCode 13 and then performs the click() event on $(#campus-search) if that keycode is passed (by an enter press).
Demo
This is what you are looking for:
HTML:
<input id="keywords" type="text" value="" />
<input id="campus-search" type="button" value="Campus Search" />
JavaScript / jQuery:
$("#keywords").keypress(function (e) {
if (e.charCode === 13) {
$("#campus-search").click();
} else {
$("#keywords").val($("#keywords").val() + String.fromCharCode(e.charCode));
}
});
$("#campus-search").on("click", function () {
alert("Searching..");
});
Live Demo
I have a requirement where user cannot submit the form if he press enter key unless focus will be on submit button.
Using following code, I am able to do that, but now the issue is, if I have any enter key event attached specific to any field (e.g. if I want to attach enter key event to one textfield for some special requirement), it is not allowing me due to the script I have written below..
<script>
$(document).keydown(function(event) {
if (event.keyCode == 13) {
var $focusedItem = $(document.activeElement);
if($focusedItem.is("button") || $focusedItem.is("a") || $focusedItem.attr("type") == "submit") {
$focusedItem.click();
}
else {
event.preventDefault();
}
}
});
</script>
Any solution where I can restrict user from submitting form on pressing enter key, if focus is not on the submit button but at the same time if there will be any enter key event attached to any form-field, that should also work.
If you had created a JsFiddle it would be easier to help. However, I'm thinking you should do something like this:
if($focusedItem.attr('id') == 'submitButton') {
if (event.keyCode == 13) {
submit the form
}
}else if ($focusedItem.attr('id') == 'Anothertextarea') {
if (event.keyCode == 13) {
do something special
}
}else{
if (event.keyCode == 13) {
return null;
}
}
Remove the line event.stopPropagation(); from your script, you need only the preventDefault() (prevents the submit).
When you do stopPropagation() you are stopping all other keypress events on the element.
Try that and see if it fits your needs:
--DEMO--
$(document).on('submit', 'form', function (e) {
e.preventDefault();
}).on('click', ':submit', function (e) {
if (!$(document.activeElement).is(':submit')) return;
var form = $(this).closest('form').length ? $(this).closest('form')[0] : $('#' + $(this).attr('form'))[0];
form.submit();
});
Maybe I'm missing the point, this is basically a standard html issue.
Don't give the form an submit action (move it to a click event directly on the button) and change all button types to button instead of submit.
I can't remember if simply removing the submit from the form is enough. If not then just do onSubmit="return false;" I think that does it.
However as a note the requirement for this as a global behavior is probably wrong and if its for the government then you will probably get in trouble since its not compliant with accessibility guidelines.
On a page I have a google search-field and a separate form for a login. In order to make the search-field work with enter, I included the following script:
$('#searchBox').keydown(function (event) {
if (event.keyCode == 13) {
document.location.href = "someTargetPage.html";
}
});
The only problem is that in that case the form would be sent because the search-field is included within the form, which I can't change due to the architecture of dot net nuke. I tried to prevent that like this:
$('form').delegate('input:submit', 'click',
function () {
return false;
});
Now the search-field does work nicely with enter, but the submit-button from the form won't work! Is there a way to check from where the trigger comes and either allow or deny it?
Thx for any tipps!
Remove your code that stops the input button from working (your delegate on input:submit). You just need to make #searchBox not propagate the event up to the form. It's the search box handler that needs to cancel the event by returning false:
$('#searchBox').keydown(function (event) {
if (event.keyCode == 13) {
document.location.href = "someTargetPage.html";
return false;
}
});
if you actually want to totally disable the form, just return false on it's onsubmit event:
$("#searchform").live("onsubmit", function(){ return false; });
I had a simple script that when you pressed C you'd be redirected to a different page, same for other letters.
However, every time you would press the button this would happen, even if you were typing text into an input text field.
Can anyone write a lightweight script to allow me to make multiple hotkeys without them working in input fields or can show me where I can find documented explanations for this?
Okay, so I have the hotkey working, just can't make it stop.
$("input.registerform").keypress(function(e){
e.stopPropagation();
});
Here is what I have to make it stop, the class of my input form is registerform bgcolor2 but it won't work with input.registerform, nor with input.registerform bgcolor2.
I tried adding an ID to it with registerform as ID; didn't work either :/
Is it being caused by my AJAX? or am I missing something here?
Try this
$(document).keypress(function(e){
if(e.which == 13){
//Enter key is press do what you want
}
else if(e.which == 67 || e.which == 99){
//C key is press do what you want
//window.location.href = "urlToRedirect";
alert("C pressed");
}
else if(e.which == 32){
alert("Space pressed");
}
//Similarly check for as many conditions you want for different keys(ascii code)
});
//To supress this behavior do not happen in input field stop the event propagation
$("input").keypress(function(e){
//code goes here
e.stopPropagation();
});