Default button on enter and popup list - javascript

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

Related

disable a textarea with angularjs

I am trying to disable a textarea from handling a keyboard event when ever a user presses the enter key of the keyboard when the textarea is empty using angularjs. I have been able to disable the submit button when the textarea is empty but I am trying to disable the textarea when from enter event when the textarea is empty.
This is my attempt:
<div class="descriptionarea">
<textarea ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div>
When I hit enter from my textarea it triggers event using the following code
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { // enter key press
send();
}
});
The above code works whether the textarea is empty or not.
EDITTED:
In my app.js of angularjs
app.controller('TodoCtrl',function($scope){
//handle javascript enter event on key up
// function TodoCtrl($scope) {
$scope.trackTxt;
$scope.send = function($event){
alert('TEST');
}
$scope.isEmpty = function(param){
return param.trim().length === 0;
}
//}
});
In jsp file
<div ng-controller="TodoCtrl">
<textarea ng-keyup="$event.keyCode == 13 && !isEmpty(trackTxt) && send($event)" ng-model="trackTxt" id="input" ></textarea>
<span class="buttonfortxtarea">
<button ng-disabled="!trackTxt" ng-click="send($event)" class= "btn btn-mini description_submit" id="new-chat-button">Submit</button></span>
</div></div>
Please how can I use angularjs to prevent the enter event from happening when ever the text-area is empty.
You can use ng-keyup for attaching an function on enter key press,
ng-keyup="$event.keyCode == 13 && functionToCall()"
Here is demo,
Thanks
You could simply check if it's empty...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val() != "") { // enter key press
send();
}
});
This also may work:
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
send();
}
});
To prevent the default enter use preventDefault() Event Method
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
});
How about the sendChat()...
document.getElementById('input').addEventListener('keyup', function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13 && $(this).val().length <= 0) { // enter key press
e.preventDefault(); //This avoid the enter...
}
else if(code == 13 && $(this).val().length > 0) {
sendChat();
}
});

How to handle multiple buttons enter key functionality?

In my page there are two buttons. For enter key functionality I have written the following jQuery code.
$(function () {
$("#first-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
$("#second-button-id").keyup(function (e) {
if (e.keyCode == '13') {
e.preventDefault();
}
}).focus();
});
But always when click on enter key first one is firing. Please tell me how to handle the multiple button enter key functionality.
Try something like this
HTML :
<label>TextBox : </label>
<input id="textbox" type="text" size="50" />
<label>TextBox 2: </label>
<input id="textbox2" type="text" size="50" />
JQuery
$('#textbox , #textbox2').keyup(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed a "enter" key in textbox');
}
event.preventDefault();
}).focus();
DEMO
Some browser prefer keycode and other use which ... I suggest you to use both..
You do not need to focus on two buttons at the same time. Try doing something like this:
$("#button1").keypress(function(event){
if ( event.which == 13 ){
//Do something}
$("#button2").keypress(function(event){
if( event.which == 13 ){
//Do something else}
The problem i think is with your event.preventDefault() function which stops the propogation of the event once a function is executed. In your case, your first function might be getting completed before the second one and hence the second one gets aborted in the middle.
$("#first-button-id , #second-button-id ").keyup(function(event){
if ( event.which == 13 ) {
alert("you pressed enter.");
event.preventDefault();
}
}
The reason the first submit button is always firing is because that's the default behavior of a web page which you haven't actually altered with your code.
Try this:
$(function () {
$("#first-button-id, #second-button-id").keyup(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
if (e.keyCode == '13') {
$(this).trigger("click");
}
});
});
What you seem to be asking about strikes me as rather odd. It looks like you want second-button to be 'clicked' if the focus is on second-button and enter is pressed. Tabbing until the focus is on the correct button is really the only practical way this could happen.
Try this.
$('#first-button-id').on("keydown", function (e)
{
if (e.keyCode == 13)
{
e.preventDefault();
$("first-button-id").click();
}
});

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

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

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