Detect the cursor location - javascript

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

Related

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.

Form submission on pressing enter button

I am handling ajax suggestions using keyboard and mouse, it is capturing every keyevent except enter key(13). What I want is to get the "selected suggestion value" into the text box. For this I am handling keyevent = 13. Now the problem is when I am pressing enter key, my form get submitted instead of going into the "if block" where I am checking (keyevent = 13).
I am using struts <html:submit> tag to submit my form. I guess, the browser automatically set the focus into first <html:submit> tag that comes in its place. How to defocus this? I tried setting focus at other fields but trick doesn't work.
The other way is, I can use simple <html:button> and can get the things working, but the system already using <html:submit>. So, getting approval and modification is quite hectic.
Code for submit button:
<html:submit styleClass="btn" property="method.saveVisaRequestForRMG" onclick="bCancel=false" styleId="submitBtn">
and code for event handling:
// Handle ENTER key
case 13: handleSelectedItem(obj, container, cur);
ev.cancelBubble = true;
break;
How to come out of this problem? Please suggest me.
If you use jquery there is a simple way to handle enter press events:
$(window).keypress(function(e) {
if(e.keyCode == 13) {
e.preventDefault();
alert('Enter!');
}
});
After you prevented the default event you can do whatever you want for example posting the data into the server, saying hello or whatever :)
Try to return false; to cancel the event handling of the submit?
Do you have something like:
onsubmit="return formValidator()"

how to remove the default focus on submit button in HTML form?

I have a HTML form on my page. When i am putting some value in one of the text fields in form and press 'Enter key' the form gets submitted instantly. I think this is happening due to default focus is on submit button. But i try to remove that focus using blur() function, it is not working. I am using Chrome.
Is there any way to avoid this scenario?
All suggestions are welcome. thanks in advance.
The Submit button is not actually focused; Enter in a text field is supposed to submit the form.
You could register a handler for the submit event, and then only allow it if the Submit button was actually focused at the time submit was requested.
However, you'll be deliberately breaking the way that HTML forms work. Not everyone wants to submit the form using the One True Way of actually clicking the Submit button (also, you'll be breaking accessibility and may introduce browser-specific bugs).
No. The focus is still on the text field. Pressing enter there is supposed to submit the form (and bypasses the submit button entirely).
You can suppress the behavior using JavaScript, but since it is normal behavior for the browser, I wouldn't recommend doing so.
try this solution: replace the 'input' with 'button' and add attribute
type equals 'button' and handle the onclick event with submit javascript function
<form name='testForm'>
<input type='text' value="myName" />
<button type='button' onclick='testForm.submit()'/>
</form>
i think it works also with tag input adding the same attribute
Enjoy
Mirco
blur() is the way to go. It works like this:
<button onclick="this.blur();">some button</button>
Note that you should not use JavaScript and DOM-events using Attributes. This is just for demonstration purposes. Try to be unobstrusive.
Maybe it will help you out, the form is "supposed" to be sent with enter in the text box (HTML by design), it is no a matter of focus.
If you want to avoid it, check this out.
This is the proposed script:
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
Good luck, tell me if you need any clarification!
EDIT: I do agree with Piskvor answer, it may bring some bugs
this has nothing to do with the focus, its just the default behavior of you browser. to avoid this, you could try to cath the enter-keypress like this (Source - but there are a lot of other solutions (most working the same way, just using other events like the firms onsubmit instead of the documents onkeypress)):
function catchEnter(e){
// Catch IE’s window.event if the
// ‘e’ variable is null.
// FireFox and others populate the
// e variable automagically.
if (!e) e = window.event;
// Catch the keyCode into a variable.
// IE = keyCode, DOM = which.
var code = (e.keyCode) ? e.keyCode : e.which;
// If code = 13 (enter) or 3 (return),
// cancel it out; else keep going and
// process the key.
if (code == 13 || code == 3)
return false;
else
return true;
}
// Anonymous method to push the onkeypress
// onto the document.
// You could finegrain this by
// document.formName.onkeypress or even on a control.
window.onload = function() { document.onkeypress = catchEnter; };
Change:
<input type="text" ... >
To:
<textarea ... ></textarea>
You may need to mess around with the attributes a bit, I've left them signified as ....
try to add on the keypress event of your button this javascript function :
function ButtonKeyPress()
{
var code = (window.event.which) ? window.event.which : window.event.keyCode;
if ( code == 13 )
{
event.returnValue = false;
return false;
}
return true;
}
So, you have a form. In this form, you have a text input, and a submit button.
You get in the text input, you type some text, than you press "Enter". This submits the form.
You would like to break this normal behavior.
I think this is not a good idea : The convention says that when your in a text input and press "Enter", it submits the form. If you change this behavior, users could be (I don't find the right word, let's say ~) surprised.
Anyway, if you still want to do this, you should listen for the keypress event on the text input, and than prevent default behaviour shoud do the work.
let's say you use jQuery :
$(input[type=text]).bind('keypress', function(evt) {
if(evt.keyCode == 13) {
evt.preventDefault();
}
});
This should do it. I didn't test it, maybe I made mistakes, but you got the idea, no ?
And maybe keyup is better than keypress... I don't know very well this, not enough practice on key bindings
The easiest way is to set css style like this:
&:focus {
outline: 0 none;
}

How to block form submission when the enter key or return key is pressed?

I have a form that I use JQuery, I don't think I need to put code in this post, the question is pretty basic.
But I would like to block the form from submitting when people press the Enter Key or the Return Key.
At the same time, I have textareas, where the user will need to be able to press the Enter / Return keys.
A quick and nasty hack but generally more reliable than trying to block keypresses in every field: add:
<input type="submit" onclick="return false;" />
at the top of the form. The first submit in a form acts as a default button for when Enter is pressed in current browsers, so by neutering it you prevent an Enter-submission from occurring.
Then use CSS to hide and/or move the button so it can't be seen.
It isn't always a good idea to block Enter-submissions though; it's the standard way the browser is expected to work and some users really do want it.
set a flag at the document level, submitform = false;
validate submissions against this.
change the flag in the onclick handler of the submit button.
Couldn't you add an onsubmit attribute to the form, then check if it was submitted using the enter key?
You could try this
jQuery(document).ready(function(){
validSubmit = false;
})
jQuery('myForm textarea').keypress(function(e) {
if (e.which == 13) {
validSubmit = true; // if the pressed key is enter, then allow submissions
}
})
jQuery('myForm').submit(function(){
if (!validSubmit) {
return false; //if submitting the form is not allowed, then cancel submission
}
})
This cancels all submissions whatsoever unless the enter/return key is pressed on a textarea. If you are using a button, you need to add a function to that too.
jQuery('form button.validSubmit').click(function(){ //or 'form input[type="submit"]'
validSubmission = true;
})

Categories

Resources