How can I use the KeyDown event with the exception of backspace? - javascript

I have a file with multiple inputs. I have a Javascript function which writes information about the input and I do not want it triggered when the user is pressing backspace.
EDIT: Question: Why does this code not work in terms of preventing backspace execution? Instead the entire function does not work:
function hide_words(z,x)
{
if(event.key == 8)
{
event.preventDefault();
}
document.getElementById(z).innerHTML = x;
}
The above just stops the functioning from executing all together.

Update this to:
function inputOn(event)
{
if(event.keyCode == 8)
{
event.preventDefault();
}
}
document.getElementById("input").addEventListener("keydown", inputOn, false);
<input id="input" style="width: 400px;" value="try to delete any text using backspace." />
preventDefault will cancel out the normal action. So the backspace won't do a thing. A keyDown is cancelable, so this works. Please note that the input of other keys is still possible.
You might also want to catch keyCode 46 which is the delete button.

Related

How do I prevent the hotkey ` from being added to a html form input?

I used the instructions here to turn ` into a shortcut thusly:
function reset_shortcut_key(e) {
if (e.keyCode == 192) reset_data();
}
document.addEventListener('keyup', reset_shortcut_key, false);
It loads the next problem successfully, but when I hit this hotkey while focused on a <form> <input> </form> environment, the ` character momentarily shows up (before the next problem is loaded).
I want to prevent it from showing the ` character.
Question: How do I prevent the hotkey ` from being added to a form input?
Other related questions are How can I prevent \ from being added from the form input? (but this is about stripping slashes) and Javascript -> Hotkeys -> Disable for input fields (and here) (but I want the hotkey to work).
Edit: Judging from the current comment and answer, the appropriate function is event.preventDefault(). I'm still not clear on how to actually implement this.
Simply adding it before or after document.addEventListener('keyup', reset_shortcut_key, false); doesn't do anything. Beyond this,
document.addEventListener("keyup", function(event) {
event.preventDefault();
reset_shortcut_key();
}, false);
and
document.querySelector("#input-guess").addEventListener("keyup", function(event) {
event.preventDefault();
reset_shortcut_key();
}, false);
(where id="input-guess" is the name of my <input>) both prevent reset_shortcut_key() from being called. Modifying reset_shortcut_key as follows doesn't change anything:
function reset_shortcut_key(e) {
e.preventDefault();
if(e.keyCode == 192) reset_data();
}
At this point, I'm just making guesses on what to do.
Have you tried this?
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
event.preventDefault();
It turns out that there was a second issue: I needed to use keydown (instead of keyup). After making that change, the following code (utilizing preventDefault()) works:
function reset_shortcut_key(e) {
if(e.keyCode == 192) {
e.preventDefault();
reset_data();
}
}

Determine if input field is in edit mode

I have a form where if the user presses ESC it is closed. Anytime a field is changed I run code to save the value based on onchange events. So typically all fields have been committed before the ESC key has been hit.
However, if the user clicks in the field and changes the value but doesn't tab or hit enter the onchange doesn't fire. So then the change is not committed.
And while the field is in the edit state the following code doesn't run when the ESC key is pressed.
Is there a way to change the functionality of the ESC key while a field is still in the edit mode?
$(document).keyup(function (e) {
if (e.keyCode == 27) {
// this assumes all of the fields have been committed.
$('#dialog-form').dialog('destroy').html('');
}
}
If you want to change the behaviour of ESC while editing the form, consider that if you listen to the document, you can detect keypresses from anywhere. If you listen to only your form, you will only detect keypresses from within that form.
<form id="foo">
<input type="text" />
</form>
<script>
$("#foo").keyup(function (e) {
if (e.keyCode == 27) {
// This code will run if you press escape while editing the form.
}
})
$(document).keyup(function (e) {
if (e.keyCode == 27) {
// This code will run if you press escape from anywhere.
}
})
</script>
For your other problem, I don't think elements have a .dialog() method.

jQuery keypress to work normally except hitting enter

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

form should not submit on enter if focus is not on submit button

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.

jquery disable form submit on enter

I have the following javascript in my page which does not seem to be working.
$('form').bind("keypress", function(e) {
if (e.keyCode == 13) {
e.preventDefault();
return false;
}
});
I'd like to disable submitting the form on enter, or better yet, to call my ajax form submit. Either solution is acceptable but the code I'm including above does not prevent the form from submitting.
If keyCode is not caught, catch which:
$('#formid').on('keyup keypress', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
EDIT: missed it, it's better to use keyup instead of keypress
EDIT 2: As in some newer versions of Firefox the form submission is not prevented, it's safer to add the keypress event to the form as well. Also it doesn't work (anymore?) by just binding the event to the form "name" but only to the form id. Therefore I made this more obvious by changing the code example appropriately.
EDIT 3: Changed bind() to on()
Usually form is submitted on Enter when you have focus on input elements.
We can disable Enter key (code 13) on input elements within a form:
$('form input').on('keypress', function(e) {
return e.which !== 13;
});
DEMO: http://jsfiddle.net/bnx96/325/
Even shorter:
$('myform').submit(function() {
return false;
});
$('form').keyup(function(e) {
return e.which !== 13
});
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
which docs.
$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
if(e.which == 13) {
e.preventDefault();
return false;
}
});
This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.
Most answers above will prevent users from adding new lines in a textarea field. If this is something you want to avoid, you can exclude this particular case by checking which element currently has focus :
var keyCode = e.keyCode || e.which;
if (keyCode === 13 && !$(document.activeElement).is('textarea')) {
e.preventDefault();
return false;
}
if you just want to disable submit on enter and submit button too use form's onsubmit event
<form onsubmit="return false;">
You can replace "return false" with call to JS function that will do whatever needed and also submit the form as a last step.
The simple way is to change type of button to button - in html and then add event in js...
Change from this:
<form id="myForm">
<button type="submit">Submit</button>
</form>
To
<form id="myForm">
<button type="button" id="btnSubmit">Submit</button>
</form>
And in js or jquery add:
$("#btnSubmit").click(function () {
$('#myForm').submit();
});
The overkill of having to capture and test every keystroke for the ENTER key really bugs me, so my solution relies on the following browser behavior:
Pressing ENTER will trigger a click event on the submit button (tested in IE11, Chrome 38, FF 31) **
(ref: http://mattsnider.com/how-forms-submit-when-pressing-enter/ )
So my solution is to remove the standard submit button (i.e. <input type="submit">) so that the above behavior fails because there's no submit button to magically click when ENTER is pressed. Instead, I use a jQuery click handler on a regular button to submit the form via jQuery's .submit() method.
<form id="myform" method="post">
<input name="fav_color" type="text">
<input name="fav_color_2" type="text">
<button type="button" id="form-button-submit">DO IT!</button>
</form>
<script>
$('#form-button-submit').click(function(){
$('#myform').submit();
});
</script>
Demo: http://codepen.io/anon/pen/fxeyv?editors=101
** this behavior is not applicable if the form has only 1 input field and that field is a 'text' input; in this case the form will be submitted upon ENTER key even if no submit button is present in the HTML markup (e.g. a search field). This has been standard browser behavior since the 90s.
You can do this perfectly in pure Javascript, simple and no library required. Here it is my detailed answer for a similar topic:
Disabling enter key for form
In short, here is the code:
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>
This code is to prevent "Enter" key for input type='text' only. (Because the visitor might need to hit enter across the page) If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
I don't know if you already resolve this problem, or anyone trying to solve this right now but, here is my solution for this!
$j(':input:not(textarea)').keydown(function(event){
var kc = event.witch || event.keyCode;
if(kc == 13){
event.preventDefault();
$j(this).closest('form').attr('data-oldaction', function(){
return $(this).attr('action');
}).attr('action', 'javascript:;');
alert('some_text_if_you_want');
$j(this).closest('form').attr('action', function(){
return $(this).attr('data-oldaction');
});
return false;
}
});
In firefox, when you at input and press enter, it will submit it's upper form. The solution is in the will submit form add this:
<input type="submit" onclick="return false;" style="display:none" />
$('#FormID').on('keyup keypress', function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
});
The following code will negate the enter key from being used to submit a form, but will still allow you to use the enter key in a textarea. You can edit it further depending on your needs.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && ((node.type=="text") || (node.type=="radio") || (node.type=="checkbox")) ) {return false;}
}
document.onkeypress = stopRKey;
</script>
3 years later and not a single person has answered this question completely.
The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.
Assuming the form has a submit button, whether a <button id="save-form"> or an <input id="save-form" type="submit">, do:
$("#save-form").on("click", function () {
$.ajax({
...
});
return false;
});
Here is a simple JavaScript solution without using different variations of handling keydown or keypress events:
document.forms[0].addEventListener('submit', function(e) {
if(document.activeElement.getAttribute('type') !== 'submit') {
e.preventDefault();
}
});
Submitting the form will occur only when the active element on your page is the submit button.
So you can submit the form by clicking on your submit button or by pressing the ENTER key when the submit button has focus.
I heard which is not recommended, so change Best rated answer to this.
$('#formid').on('keyup keypress', function(e) {
if (e.key === 'Enter') {
e.preventDefault();
return false;
}
});
ref. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
When the file is finished (load complete), the script detect each event for " Entry " key and he disable the event behind.
<script>
$(document).ready(function () {
$(window).keydown(function(event){
if(event.keyCode == 13) {
e.preventDefault(); // Disable the " Entry " key
return false;
}
});
});
</script>
Complete Solution in JavaScript for all browsers
The code above and most of the solutions are perfect.
However, I think the most liked one "short answer" which is incomplete.
So here's the entire answer. in JavaScript with native Support for IE 7 as well.
var form = document.getElementById("testForm");
form.addEventListener("submit",function(e){e.preventDefault(); return false;});
This solution will now prevent the user from submit using the enter Key and will not reload the page, or take you to the top of the page, if your form is somewhere below.
How about this:
$(":submit").closest("form").submit(function(){
$(':submit').attr('disabled', 'disabled');
});
This should disable all forms with submit buttons in your app.

Categories

Resources