Need the function to be triggered on hit of enter - javascript

I have a search box whch is a text type. it has a click button, which initiates the Find().
how can i do the find by hitting enter inside the textbox

If your text input is inside of a form element, you can attach an onSubmit (or jQuery .submit()) event handler to the form element. This event will fire when the user presses enter while inside the text input

Use ng-keypress on the input element and check for enter key code:
<input type="text" ng-keypress="($event.which === 13) ? Find() : void(0)" />
This is assuming that jQuery has been loaded. Otherwise, you might want to use $event.keyCode, but doing it in a browser compatible way would be tricky.
If you have a directive which contains this template, then you should catch this event in the link function and call Find there. Otherwise, putting the input button inside a form and defining a on-submit on the form element. Do check for IE compatibility though, I remember IE7 at least needs a hidden <input type="submit" /> in the form for the enter key to submit the form.

document.onkeydown = function(evt) {//when key is pressed
evt = evt || window.event;
if (13 == evt.keyCode) {//if key was enter
if (document.activeElement.className== "search_input"){//if the focus is on your input (in this case search_input)
Find() //call your function
return false;//cancel enter
}
}
}

I generally have very good luck with Angular-UI. The ui-keypress directive should serve well in this case. http://angular-ui.github.io/ui-utils/#/keypress. The keycode you want for the Return/Enter key is 13.

Related

Angular 9 : Detect enter key incase of empty form

I am trying to detect the enter key event when on a form submit, The enter key event works only if there any value present in any of the form components.
But the enter key event is not working in the case of the empty form (ie no value present in any of the form elements)
<form (keydown)="keyDownFunction($event)">
<input type="text" />
</form>
Ts file
keyDownFunction(event) {
if (event.keyCode === 13) {
alert("you just pressed the enter key");
// rest of your code
}
}
Here is the stackbliz URL https://stackblitz.com/edit/angular-7v744e
It's a matter of the focus. If you hit enter while your cursor is not focused on the form, the event won't register, similar to if you have a click event and you click outside of the scope.
If you're in focus, the enter will be caught, even if the form is empty.
To get around this, you should have your form in focus as soon as it loads. This answer here shows one way to achieve this, and this answer shows another.

EventListeners - Javascript [duplicate]

I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.
I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:
$('form').keypress( function( e ) {
var code = e.keyCode || e.which;
if( code === 13 ) {
e.preventDefault();
return false;
}
})
As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.
Does anyone know of a more sophisticated technique for doing this?
Similarly, are there any pitfalls to this solution that I'm just not aware of?
Thanks.
Using
<button type="button">Whatever</button>
should do the trick.
The reason is because a button inside a form has its type implicitly set to submit. As zzzzBoz says, the Spec says that the first button or input with type="submit" is what is triggered in this situation. If you specifically set type="button", then it's removed from consideration by the browser.
It is important to read the HTML specifications to truly understand what behavior is to be expected:
The HTML5 spec explicitly states what happens in implicit submissions:
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).
Edit to add:
The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.
Where ever you use a <button> element by default it considers that button type="submit" so if you define the button type="button" then it won't consider that <button> as submit button.
I don't think you need javascript or CSS to fix this.
According to the html 5 spec for buttons a button with no type attribute is treated the same as a button with its type set to "submit", i.e. as a button for submitting its containing form. Setting the button's type to "button" should prevent the behaviour you're seeing.
I'm not sure about browser support for this, but the same behaviour was specified in the html 4.01 spec for buttons so I expect it's pretty good.
By pressing 'Enter' on focused <input type="text"> you trigger 'click' event on the first positioned element: <button> or <input type="submit">. If you press 'Enter' in <textarea>, you just make a new text line.
See the example here.
Your code prevents to make a new text line in <textarea>, so you have to catch key press only for <input type="text">.
But why do you need to press Enter in text field? If you want to submit form by pressing 'Enter', but the <button> must stay the first in the layout, just play with the markup: put the <input type="submit"> code before the <button> and use CSS to save the layout you need.
Catching 'Enter' and saving markup:
$('input[type="text"]').keypress(function (e) {
var code = e.keyCode || e.which;
if (code === 13) {
e.preventDefault();
// also submit by pressing Enter:
$("form").submit();
}
});
Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.
You can use javascript to block form submission until the appropriate time. A very crude example:
<form onsubmit='return false;' id='frmNoEnterSubmit' action="index.html">
<input type='text' name='txtTest' />
<input type='button' value='Submit'
onclick='document.forms["frmNoEnterSubmit"].onsubmit=""; document.forms["frmNoEnterSubmit"].submit();' />
</form>
Pressing enter will still trigger the form to submit, but the javascript will keep it from actually submitting, until you actually press the button.
Dom example
<button onclick="anotherFoo()"> Add new row</button>
<input type="text" name="xxx" onclick="foo(event)">
javascript
function foo(event){
if(event.which == 13 || event.keyCode == 13) // for crossbrowser
{
event.preventDefault(); // this code prevents other buttons triggers use this
// do stuff
}
}
function anotherFoo(){
// stuffs.
}
if you don't use preventDefault(), other buttons will triggered.
I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.
My situation has two Submit buttons within the form element: Update and Delete. The Delete button deletes an image and the Update button updates the database with the text fields in the form.
Because the Delete button was first in the form, it was the default button on Enter key. Not what I wanted. The user would expect to be able to hit Enter after changing some text fields.
I found my answer to setting the default button here:
<form action="/action_page.php" method="get" id="form1">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</form>
<button type="submit" form="form1" value="Submit">Submit</button>
Without using any script, I defined the form that each button belongs to using the <button> form="bla" attribute. I set the Delete button to a form that doesn't exist and set the Update button I wanted to trigger on the Enter key to the form that the user would be in when entering text.
This is the only thing that has worked for me so far.
You can do something like this.
bind your event into a common function and call the event either with keypress or button click.
for example.
function callME(event){
alert('Hi');
}
$('button').on("click",callME);
$('input ').keypress(function(event){
if (event.which == 13) {
callME(event);
}
});
I added a button of type "submit" as first element of the form and made it invisible (width:0;height:0;padding:0;margin:0;border-style:none;font-size:0;). Works like a refresh of the site, i.e. I don't do anything when the button is pressed except that the site is loaded again. For me works fine...

How to disable the enter button from triggering the onkeyup event?

In my asp.net solution, I have a text input box and a search button. There is a onkeyup jquery event on the text input field so it automatically clicks the search button when the user presses a key. You can also manually click the button.
But what I noticed is that if you are typing, and then you press ENTER key, it will trigger the on onkeyup event. How can I disable the function from occurring if the ENTER key was pressed, or maybe detect if it was the ENTER key and then have an if statement or something.
Another thing that is happening is, if there is something wrong with the text in the input box, I display an alert message box. Then if you press ENTER to close the box, it will somehow trigger the onkeyup event, which displays the alert box again...
Thanks.
add if (evt.keyCode != 13) in front of all actions in the function :)
You can use .which on the event to determine the KeyCode for the key that was pressed (ENTER = 13):
$('#input').keyup(function(event) {
if(event.which == 13)
{
//respond to enter keypress
}
});
Also you can use this site to easily find info about keyups/downs etc for different keys.
Hope this helps!
Hope this helps.
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
The onkeyup event is triggered after an alert when you close it with ENTER because the alert is close onkeydown, and so after it's closed and the document regains focus, when you release the key, the textbox's onkeyup event will be triggered.
As previously stated, you can add an if (event.keyCode != 13) to test if the ENTER key is not the key that was pressed.
A better solution would be to use a different event.
Instead of onkeyup, use oninput.
The oninput event is triggered when the user changes the textbox's value.
The event will fire only when the user writes something in the textbox or deletes something. It will not go off when the ENTER key is pressed, or when any other key that doesn't change the textbox's value (like arrow keys) is pressed.
The oninput event might be a better choice for the functionality you're searching for.
*if you're using the oninput event you don't need the if mentioned before.
A fiddle for demonstration of the oninput event: Here
For future reference I found this useful site:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
Good luck!

how to detect if wrong key is typed in <input>?

We have a simple html text input:
<input type=text /> - all I try to do is add event to fire when user will try to input certaing characters, for example space. So I can alert user while he is typing that these character are not allowed.
to extend rcravens answer a little, I would use the onkeyup event as I have had issues with IE not registering what key fired the event on the onkeydown. You can then process the keycode for the event to determine what actions you want to take.
function getCode(e) {
var src = get your event however you do so.
var code = evt.charCode || evt.keyCode;
switch (code) {
// do something here.
}
}
<input type="text" onkeyup="getCode()">
Good resource: Quirksmode.org
and here: character codes
Catch both onchange event and onkeyup event. onchange only gets fired when the user tabs to another control. onkeyup will get fired for every typed character. Not sure about when the user pastes something in.
<script>
function OnChangeOccurred(evt) {
var str = evt.currentTarget.value; // this is the current text in the input box
}
</script>
<input onchange="OnChangeOccurred(event);" onkeyup="OnChangeOccurred(event);" />
Try JavaScript's onkeypress event.
http://www.w3schools.com/jsref/event_onkeypress.asp
This should get you started. You can then intercept all keys and echo their values to determine the ones you want. Be sure to test crossbrowser compliance.
Bob

Mouse & keyboard event names in JavaScript

I want to ask a question about the JavaScript event. I have an <input type="text"> box and I have applied the autocomplete function on that box.
I know that when the user types the char like "sta" in the box and the JavaScript will call the keypress event, which also calls the autocomplete function.
However, I want to know what event of the JavaScript will be called what I use the mouse to click/click the keyboard "enter" to the wanted item from the autocomplete list.
The mouse clicking event is called onclick, the enter key event is called an onkeyup event. For the second one, you need to make sure the enter key was pressed, though:
someElement.onkeyup = function( e ){
var e = e || window.event;
if( e.keyCode == 13 ){
// enter was pressed!
}
};
However, I want to know what event of the JavaScript will be called what I use the mouse to click/click the keyboard "enter" to the wanted item from the autocomplete list.
It sounds like you are looking for an event which triggers after text of the text box changes. If that is the case, the event fired is onchange.
That will take care if user select autocomplete option either via mouse or hits the enter button.

Categories

Resources