Prevent enter key on html input field react.js - javascript

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();
}
}

Related

In HTML form, can we validate the text fields while the user is filling in the form

Is it possible to validate the text fields while user is entering the data?
For instance, If the user selects one checkbox in the form, does not enter data in the text field, and moves on to the next checkbox, the form should generate an error immediately, prompting the user to enter data for the previously selected checkbox. In other words, user will not be able to proceed unless each section
is done correctly (vs. error messages at the end of the form when the submit button is clicked)
Thank You!
There are plenty of plugins that will do this for you.
jQuery form validation plugin: This one is good
If you are determined to do it manually then you would want to use something like:
$('input').on('change', function(){...});
Here are some examples for javascript blur/focus:
https://javascript.info/focus-blur
For something you can play with, here's a jsfiddle I threw together. It uses jQuery's on focus and blur events. It checks if any of the previously "required" fields were left blank (or unchecked).
$(document).ready(function() {
function checkCheckbox(jEl) {
return jEl.is("input[type='checkbox']:checked");
}
function checkTextbox(jEl) {
return jEl.is("input[type='text']") && jEl.val() != ""
}
function validate(el) {
el.parent('div')
.prevAll('div:has(".required")')
.add(el.parent('div'))
.addClass('error')
.each((i, e) => {
jEl = $(e).children('.required');
if (checkCheckbox(jEl) || checkTextbox(jEl)) {
$(e).removeClass('error');
}
})
}
$(".required").on("focus blur", function() {
validate($(this))
});
});

Make the Enter key to not create a line break

I have a textarea field and it's data will be submitted using java script and ajax by pressing enter key, the problem is that when the user press the enter key first it will create a new line then the textarea will be submitted, and i don't want it to create a new line.
Please help!
Just listen to the keydown event and prevent the default action (which is the linebreak)
$("textarea").on("keydown", function(e) {
if(e.which === 13) { // enter key
e.preventDefault(); // prevents linebreak
// here you could add your submit call
return false;
}
});
You can use jQuery to determine whether the textarea is active:
$("#foo").is(":focus") // expression is true only when it is active
So your code should look something like this:
if (<enter key pressed> and !($("#foo").is(":focus")))
<submit with JavaScript and Ajax>

keyup event not triggered for escape key

I have a text input field referred to as $nameEditor. I want to show this text field when a button is pressed, and hide it on blur or when the escape key is pressed.
Hiding the field on blur works every time.
Hiding the field when pressing the escape key works only the first time. Example sequence of events.
Press the button that shows the text input field.
Press escape - text input field hides
Press the button that shows the text input field again.
Press escape - the keyup event is not triggered
Press any other key and the keyup event is triggered
Press escape - the text input field hides
Relevant markup:
<button id="renameButton" title="Rename" data-icon="ui-icon-pencil">Rename</button>
<span id="assemblyNameView">Assembly Name</span>
<input id="assemblyNameEditor" style="display:none" class="ui-corner-all widget">
Relevant script:
var $renameButton = $("#renameButton");
var $nameViewer = $('#assemblyNameView');
var $nameEditor = $('#assemblyNameEditor');
function cancelEdit() {
$nameEditor.hide();
$nameViewer.show();
}
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select();
}
function commitEdit(newName) {
// TODO: Update the structure being edited.
$nameEditor.hide();
$nameViewer.text(newName);
$nameViewer.show();
}
$renameButton.click(initEdit);
$nameEditor.blur(cancelEdit);
$nameEditor.keyup(function(e) {
console.log(e);
if (e.keyCode === 13) {
var newName = val();
if (newName === '') {
alert("No name specified.");
$nameEditor.val($nameViewer.text()).select();
e.preventDefault();
return false;
}
commitEdit(newName);
}
else if (e.keyCode === 27) {
cancelEdit();
}
});
Why is the escape key not triggering the keyup event after the input box has been hidden then re-shown?
It's hard to explain what's wrong here. There is a strange effect when both the button and the textbox receive focus? It's impossible in a standard UI interface. In fact when you type keys other than ESC, Enter, Space and maybe more ... the typed characters are shown OK in the textbox and only the textbox receives focus after that. However if you type ESC, Enter, Space... the keystrokes seem to affect on the button and I can even see there is some color effect on the button showing that it's currently focused. This looks like a bug indeed.
However to solve this, I tried using focus() explicitly appended after .select() and it works OK.
function initEdit() {
$nameViewer.hide();
$nameEditor.val($nameViewer.text()).show().select().focus();
}
Demo.

know the suggestion is opened

I have a html form with no submit button. I want to submit that form upon hitting ENTER button. I used a simple jquery code to submit the form upon hitting ENTER.
$("form :input").keypress(function(e)
{
if(e.keyCode == 13)
{
$(this).parents('form').submit();
}
});
But there is a problem with this code. When i type in text field and want to select a suggestion (these are the suggestions, suggested by browser based on the history for that field) for that field using "ENTER" key it trigger the submit of the current form. I want to skip this as well.
Is there something like in jquery or javascript
$("form :input").keypress(function(e)
{
if(e.keyCode == 13)
{
if(! $(this).is('suggestOpened')) // i want something like this
{
// submit the form
}
}
});
Thanks in advance.
No, there's no such event. You could play with onchange and onblur events to intercept whether the user is filling a particular field, but anyway without a submit button:
There's no way for the user to figure-out how to submit the form
The same action (enter key press) could lead to two different actions, which breaks UI consistency
IMHO you should definitely place a submit button.

Detect the cursor location

I have 25 components which includes [textarea, textfile, radio, combo, etc...] and I have written a key event so that when "ENTER" is entered, I call a function which will submit the page.
Now my page is getting submitted when I press enter, even in the textarea which should not be. So is there any way that I can not submit the page if it is pressed in the text area?
This happens only in IE7 and IE8; it works properly in all the other browser.
you could probably detect if any of the textarea, etc is not filled out/emtpy/unset. if all of them are filled out properly, send the form.
Did you attach the "key event" to the whole form? The whole DOM? if you did that's a normal behavior.
If you want the "Enter key" to submit the page when the focus is on the submit button then apply this functionality in the onsubmit event - there of course you can perform all the validation you need.
If you just want to exclude the enter key event from the text area - perform a simple check if the the focus is in the textarea that momemnt.
The default behaviour of a form is to submit if the user hits enter inside the form unless the focus is on a textarea, so what you want is the default behaviour. Remove whatever code you have that currently handles keypresses for the form and you'll have what you want.
I'm not sure if this will suit your needs, but you can disable the enter key inside the textarea with something like this:
$(document).ready(function(){
$('textarea').keypress(function(e){
var key = (window.event) ? e.keyCode : e.which;
if ( key == 13 ) {
return false;
} else {
return true;
}
})
})

Categories

Resources