Determine if input field is in edit mode - javascript

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.

Related

Prevent enter key on html input field react.js

I have a input field where when the user types in something, a list of options shows up underneath and the user will click on one of the options. The user can also press the Enter key as well. However, if the user were to enter something that is not in the dropdown that pops up and presses enter, my app crashes. I'm wondering if there is a way where I can disable the enter key on the input field so that when someone tries to press it, it just won't do anything.
Note that is in React as well!
Any help would be appreciated!
Thanks!
You can use onKeyDown event of the input field. You can call some method like below,
const onKeyDown = (event) => {
if (event.keyCode === 13) { //13 is the key code for Enter
event.preventDefault()
//Here you can even write the logic to select the value from the drop down or something.
}
You probably need event.preventDefault() method inside input change method.
Something like:
inputChange = event => {
if (event.target.key === 'Enter') {
event.preventDefault();
}
}

Remotely preventDefault() a Form in another Function

I'm not really sure how to ask/word this question but...
How can I prevent a form from submitting from another jQuery function? Basically, I have input fields with auto-complete functionality where the end-user can navigate through the results by using the up-and-down arrow keys. The end-user can press the Enter key to make a selection however that makes the form submit. I would like to prevent that from happening.
$('body').on('click keyup', '.inputField1', function(e) {
if(e.keyCode===13){
// Attempting to remotely prevent the form from submitting
var form = $(this).closest('form');
form.preventDefault();
form.stopPropagation();
return false;
}
// auto-complete logic below
// ...
});
Please note that I've tried adding the logic above under $('#myForm1').submit(function(e){ ... but the enter key was not detected upon input.
Assuming you're trying to prevent the form submitting when the user hits "enter" while an input field is in focus:
You want to attach this handler to the input field itself, and should use the keydown or keypress event rather than keyup (which happens after the form submission has started). What you're preventing isn't the form submit, but the default action of the event which triggers the form submit, so call preventDefault() on the event, not on the form.
event.keyCode and event.which are deprecated, but still universally supported. The currently "correct" way to do this would be if (event.key === "Enter") but this may not work in some older browsers (and note that current IE and Edge still use nonstandard identifiers for some keys.)
// It's not necessary to delegate the event from 'body', unless the form field is added to the DOM after this is called.
$('.inputField1').on('keydown', function(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://example.com">
<input class="inputField1">
<input type="submit">
</form>
Your problem is keyup on the input triggers before submit on the form.
If you change your event to keypress you'll find you can intercept the submit event before form submission.
Also, you should be using event.which instead of event.keyCode - jQuery standarizes .which but I don't think it does the same for .keyCode.
The following code sample will show this in action. The first text field will intercept when you press enter, the second will not.
(function($) {
$(function() {
$('body').on('keypress', '.a', function(event) {
if(event.which == 13) {
alert('You pressed enter');
event.preventDefault();
}
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" action="https://www.stackoverflow.com" onsubmit="alert('submit event');return false;">
<input class="a" type="text">
<input class="b" type="text">
<input type="submit">
</form>

Trying to add some form control when enter is clicked on an HTML field, getting inconsistent results

I have an HTML form that I'm running with Firefox that looks something like this:
<form name="transfer" id = "transferForm" action='transfer.php' method='POST'>
<div>
<input id="itemSelect" name="itemSelect"/>
<input type="number" name="quantity" id="quantity" value="1"
onkeypress="return isNumberKey(event)"/>
<input type="button" value="Add" id="addButton" style="width:83px"
onclick="addItem()"/>
</div>
<div>
<span id="myForm"></span>
<button id='save' name = 'save' style="width:205px">Save</button>
<button id='transfer' name='transfer' style="width:205px"/>Transfer</button>
</div>
</form>
A few things to note:
-itemSelect is a dojo/dijit combobox that is initialized elsewhere.
-The function addItem(), found in the addButton, runs some javascript that creates new elements in the span myForm each time the add button is clicked. These are processed by transfer.php when the save or transfer button is clicked.
Everything works fine, but I want to add some user friendly controls so the form can work without mouse clicking. I want the user to be able to press 'Enter' when in the "quantity" field, and have the form run the addItem() javascript and move focus back to "itemSelect".
This is the javascript I added. First, to disable the default submit on enter of the form:
<script language="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);
Then I add an event listener to "quantity"
document.getElementById("quantity").addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
//document.getElementById("addButton").click();
addItem(); //Same results using this or the line above
document.getElementById("itemSelect").focus(); //move focus back to the combo box
}
});
</script>
At first glance it appears to work, however I get two different glitches.
With this code in place, if I press enter to run the addItem() function the line gets added on the form between the span tags, but when I click "save" or "transfer" to submit the lines added this way do not not POST. In transfer.php lines that were already added show up (), but any new line added by clicking enter does not go through. However if I just click the "addButton" to add a line instead of pressing enter then it POST's just fine.
When I test adding lines with the keyboard, pressing TAB-ENTER-TAB-ENTER..., it works fine but after on about the 4th cycle the form suddenly submits to transfer.php.
So what could be going wrong with #1, and how does #2 happen?
Try the below:
Remove inline event handlers from your HTML
Seperation of concerns
Know the difference between onKeyPress Vs. onKeyUp and onKeyDown
Stackoverflow question
Prevent form submission on enter:
document.getElementById("transferForm").addEventListener("keypress", function (e) {
e = e || event;
var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
})
Call addItem on quantity input enter
document.getElementById("quantity").addEventListener("keypress", function (event) {
var keyCode = event.keyCode || event.which;
if (keyCode === 13) {
event.preventDefault();
addItem(); // addItem function call
}
});
call addItem on add button click
document.getElementById("addButton").addEventListener("click", addItem);
function addItem() {
// addItem code
}
Mitigate browser inconsistencies with javascript libraries like jQuery
In your code you might have noticed about getting the keycode value using which.
However jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

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

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.

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.

Categories

Resources