How to set the value of a textbox when it has focus - javascript

I have a textbox with a keydown handler. The handler detects if you press escape and if so it is meant to clear the textbox value. However, calling tb.value = "" normally works, unless the textbox has focus in which case it does nothing. I suspect I have to select the text and delete it, but how? This is in Firefox 12.

Have a look at this:-
LIVE DEMO
HTML:
<input type="text" id="content" />
JS:
$(document).keyup(function(e) {
if (document.activeElement.nodeName == 'INPUT')
{
if (e.keyCode == 13) { // Enter
alert('Enter Key Up');
}
if (e.keyCode == 27) { // Esc
alert('Esc Key Up');
$('#content').val("");
}
}
});

Related

Capture keyDown for current page only

I have forms on different pages of my applications. Upon pressing 'Enter' or 'Esc', the form on the current page must be 'Submitted' or 'Cancelled'. The keydown() function should be triggered anywhere on the page and not tied to a specific DOM element.
.js
$(document).keydown(function(e) {
if(e.which == 13) {
// enter pressed
$('#submitCreateAccountForm').click();
$('#submitForm').click();
$('#submitNewSubmissionForm').click();
}
if(e.which == 27) {
// esc pressed
$('#submitCreateAccountFormCancel').click();
$('#submitFormCancel').click();
$('#submitNewSubmissionFormCancel').click();
}
});
What should 'document' be replaced by? Thanks
try this
$(function(){
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
//do somethings
}
else if (e.keyCode == 27) {
return false;
}
});
});
You can try this code:
$("body").keyup(function(event){ // bind keyup event to body
if(event.keyCode == 13){ // 13 - code of enter key (find for ESC)
$("#enter").click(); // bind enter press for clicking botton with id="enter" and corresponding actions
}
});

don't can use Enter key from textarea

In my project I need diable Enter key for some textbox , because i don't want post page when enter key button . I use this Code for disable Enter key :
$(document).keypress(
function (event) {
if (event.which == '13') {
event.preventDefault();
}
});
Its work fine , but when Add textarea in page , I cant enter key for break line , because Enter key disabled .
how can I enable Enter key for textarea?
I don't know if its recommended to attach a global keypress handler like that. Regardless, the easiest way out would be
$(document).on('keypress',
function (event) {
if (event.which == '13' && event.target.tagName != 'TEXTAREA') {
event.preventDefault();
}
});
In the above, you are checking the tagName of event.target to see if the element in which the enter occured is a textarea or not
However, I would recommend this approach
$('form').on('keypress', 'form',
function (event) {
if (event.which == '13') {
event.preventDefault();
}
});
This will target all input elements and not textarea elements,
You should bind your form to detect the Enter key as,
$('#formid').on("keyup keypress", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
e.preventDefault();
return false;
}
});
Here is a demo
By this you will be able to use the Enter key on your text area without submitting the form.

Default button on enter and popup list

I'm trying to implement a form with multiple buttons on it. When I press enter I want to have my default button submitted. This code from http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/ generally works:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
});
but...
when I type in input field I have an autocomplete popup so when I press enter in this popup I expect to put this value to input field, not submit all form. Can I check somehow if this enter comes from popup? Or I should try to do this different way?
EDIT:
I think I didn't say it clear. This popup is not any part of jquery. It's standard popup that shows previously typed data into input. So it hasn't got any class nor id. Stop propagation doesn't work either. None of solutions below resolve this problem
You could use :visible to see if the dropdown div for the autocomplete is open, and then prevent the enter key action of your code completing. Something like this:
$("form input").keypress(function(e) {
var key = e.which || e.keyCode;
if (key == 13 && !$(".autocomplete").is(":visible")) {
e.preventDefault();
$('form').submit();
}
});
You could also use event.stopPropagation() on the enter key press in the autocomplete function, however you'll probably have to amend the source manually which isn't ideal.
Before return false;
write
e.preventDefault();
or/and
e.stopPropagation();
$("form input").keypress(function (e) {
if (e.target.id !== "autoCompliteId" && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
I modified my code and it works now.
I have an enum called Operation in my command and I set different value of the field before every submit button eg:
<input type="submit" value="do sth" onclick="setOperationAndSubmit('DO_STH')"/>
<input type="submit" value="next" onclick="setOperationAndSubmit('DEFAULT')"/>
function setOperationAndSubmit(operation) {
if (document.myForm.elements['operation'].value === '') {
document.myForm.elements['operation'].value = operation;
}
document.myForm.submit();
}
Then I have my action that listens to keypress and it set appropriate operation on every enter key:
$(function() {
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.myForm.elements['operation'].value = 'DEFAULT';
}
});
});
so default action is executed when I press enter

How to disable Enter/Return Key After a function is executed because of it?

I have this function where #text_comment is the ID of a textarea:
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
}
});
What is happening is the text is appending when the enter/return key is hit (keyCode 13), but it is also moving the text a line down, as the enter/return key is supposed to.
This is occurring even though I set the value of the textbox to "".
How about event.preventDefault()
Try and stop your event propagation (See http://snipplr.com/view/19684/stop-event-propagations/) when entering the if(e.keyCode == 13) case.
try this one event.stopImmediatePropagation()
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
e.stopImmediatePropagation()
///rest of your code
}
});
I've tested this out, this works. The enter does not create a new line.
$('#text_comment').live('keypress',function (e) {
if(e.keyCode == 13) {
textbox = $(this);
text_value = $(textbox).val();
if(text_value.length > 0) {
$(this).prev().append('<div id="user_commenst">'+text_value+'</div>');
$(textbox).val("");
}
return false;
}
});
Although I am wondering, if you don't want to ever have a new line, why are you using a textarea, why not use a input type='text' instead ?
Answer here http://jsfiddle.net/Z9KMb/

why is my button losing focus?

This is what I want to happen.. When a user hits 'enter' a 'SearchForItems()' should trigger. What is happening is another control, with 'other button', on the page gets focus returned to it anytime any other element is tabbed out of or after onkeyup.
I am having to force focus on the 'Search button' on page load, but after that any time enter is pressed the 'other button' is triggered. The 'other button' does not have a tab index assigned and is the pages default button.
I'm not sure if I've done a good job explaining this. Basically I want to know why focus is being shifted and how I can force the 'Search button' to trigger anytime enter is pressed.
this is one entry on my page where I'm trying to force the 'Search button' to trigger:
<td><input type="text" onkeydown="CheckForEnterKey(event)" id="AcceptedDate1" maxlength="7" style="width:121px;" value="<%=DateTime.Now.AddMonths(-3).ToString("MM/yyyy")%>"/> </td>
this is part of my jquery file where i'm also
$('#AcceptedDate1').keypress(function(e) { if (e.keyCode == 13 || e.which == 13) $('#SearchAcceptedLotsButton').click(); });
CheckForEnterKey Function
function CheckForEnterKey(e)
{
var keycode;
if(e.which)
{
keycode = e.which;
}
else
{
keycode = e.keyCode;
}
if(keycode == 13)
{
$('#SearchAcceptedLotsButton').click();//tried SearchForItems() also
}
}
Edit:
I just added this to my page and it appears to work, I added this to the main div thats holding everything together. What I need to do now is figure out where the enter was pressed so the enter is canceled everytime it is pressed within the main portion of my page. Any ideas, there are a lot of elements on my page?
function checkKey(e)
{
if(e.keyCode == 13 || e.which == 13)
{
e.returnValue = false;
e.cancel = true;
}
}
I am not sure why you are having problems. But I can offer you my onKeyDown code for pressing enter:
if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) { #DO JS HERE # }}
So I use it like this:
<input type="text" onKeyDown="if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) { alert('You pressed enter!'); }}">
In the above code whenever enter is pressed the id="SearchAcceptedLotsButton" can be triggered click as follows :
if(keycode == 13)
{
$('#SearchAcceptedLotsButton').trigger('click');
}
this is how I resolved the issue:
I added this function..
function checkKey(e)
{
if(e.keyCode == 13 || e.which == 13)
{
e.returnValue = false;
e.cancel = true;
SearchAcceptedLots();
}
}
At the top most div containing everything on the page I added this:
<div id="ItemPanel" onkeydown="checkKey(event)">
this catches every enter that is pressed within the form, canceling the default buttons behavior and calling the desired function.

Categories

Resources