Call function when press ENTER - javascript

I've this code below:
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
How can I call a JS function when I press "enter" in the input?

If you're looking to do it in raw javascript you can use the below binding to bind the enter key for the whole document to the function you wish to call.
// Load in the enter keybindings
document.onkeydown = function (e) {
switch (e.which || e.keyCode) {
case 13 : //Your Code Here (13 is ascii code for 'ENTER')
vm.clearQuery()
}
}

you can always wrap it in a form and call onsubmit and just change vm.goSearch() to your actual function.
<form onsubmit="return function(){vm.goSearch();return false;};">
<div class="search-container">
<input id="search-value" type="text" autocomplete="off" ng-model="vm.searchQuery" ng-focus="vm.searchBoxHasFocus = true" ng-blur="vm.searchBoxHasFocus = false" class="search-box-input ng-pristine ng-untouched ng-valid ng-empty" placeholder="Pesquisar" ng-enter="vm.goSearch()" ng-change="vm.getSuggestions()">
<div class="label-search" ng-click="vm.goSearch()"></div>
<button type="button" class="reset-search" ng-click="vm.clearQuery()"></button>
</div>
</form>

You can try with something like this:
// Get the input field you want
var input = document.getElementById("search-value");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
// Cancel the default action, if needed
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("ElementId").click();
//or function call here
}
});
Here is a useful tips
handle events with HTML/DOM

try ng-keypress event and read keyCode = 13 for enter.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js" >
</script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName" ng-keypress="keypress($event)">
<br>
<br>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.keypress=function(e) {
if(e.keyCode == 13) {
console.log('Enter');
}
}
});
</script>

Related

In a Vue app, Key Up Event fired on an input element when tabbed into. Why?

Here is the HTML code,
<div id="vue-app">
<h1>data binding</h1>
<label>Name:</label>
<input type="text" v-on:keyup="logName" />
<label>Age:</label>
<input type="text" v-on:keyup="logAge" />
</div>
Here is the script:
new Vue({
el: '#vue-app',
methods: {
logName: function() {
console.log("You entered your name");
},
logAge: function() {
console.log("You entered your age");
}
}
});
Now when I tab into the "Age" input field, it fires the "keyup" event. Why is that so?
tab is a key that fires the v-on:keyup event, use v-on:input event instead of it :
<div id="vue-app">
<h1>data binding</h1>
<label>Name:</label>
<input type="text" v-on:input="logName" />
<label>Age:</label>
<input type="text" v-on:input="logAge" />
</div>
This is expected behaviour, since any key press trigger a keyup event. To prevent tab key from triggering this event you could try:
methods: {
logName(e) {
if(e.keyCode === 9) return
console.log("You entered your name");
},
logAge(e) {
if(e.keyCode === 9) return
console.log("You entered your age");
}
}

HTML form input equal to var = go to URL

I have tried to create a html form where I want to be redirected to a url if the input you insert is the same as the value of a variable. I have tried to make it work in many different ways, but I have not succeeded. : - /
Someone who can help?
Here is my code:
My HTML-form:
<form autocomplete="off" onsubmit="script.js">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input id="submit" type="submit">
</form>
My JS:
var country = 'Brazil';
var input = $("input[id='myInput']").val();
$("#submit").on("submit", function(event){
if (country == input) {
window.location.href = "https://www.google.com/";
}
});
Few things. Since you are targeting the submit button and not the form, your event listener should be "click" not "submit." Next, call event.preventDefault() inside the click function. Finally, you want to get the input value after you click the button, so that assignment has to go inside your click function:
var country = "Brazil";
$("#submit").on("click", function(event) {
event.preventDefault();
var input = $("input#myInput").val();
if (country == input) {
console.log("redirect");
window.location.href = "https://www.google.com/";
} else {
console.log("don't redirect");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form autocomplete="off" onsubmit="script.js">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input id="submit" type="submit">
</form>
You need to init the value after the form is submitted otherwise it will be undefined.
var country = 'Brazil';
$("#submit").on("submit", function(event){
let input = $("input[id='myInput']").val();
if (country == input) {
window.location.href = "https://www.google.com/";
}
});
This should work:
$("#submit").on("click", function(e){
e && e.preventDefault();
var country = 'Brazil';
var input = $('#myInput').val();
if (country === input) {
window.location.href = "https://www.google.com/";
}
});
You need to get the value of the input after the click (or submit) event is fired
Place input = $("input[id='myInput']").val(); as first line inside the function which handles the submit.
So your code actually almost work. Minor adjustments:
var country = 'Brazil';
$("#submit").on("click", function(event){ // this event change to click since we change the type=submit on the input
var input = $("input[id='myInput']").val(); // this line moves inside the event
if (country == input) {
window.location.href = "https://www.google.com/";
}
else { alert('B R A Z I L type Brazil to redirect');}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form autocomplete="off" onsubmit="script.js">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input id="submit" type="button" value="GO?" /> <!-- Changed from submit to button -->
</form>
try like this
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
$('#submit').on('submit', function(event){
event.preventDefault();
event.stopPropagation();
var country = 'Brazil';
var input = $("input[id='myInput']").val();
if (country == input) {
window.location.href = "https://www.google.com/";
}
});
});
</script>
</head>
<body>
<form autocomplete="off" id="submit">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>
<input id="submit" type="submit">
</form>
</body>
</html>

how to assign the "Enter key" to an onclick event?

here i have number input bar with a tag assigned as button , i have an onclick function . how can i make the oncklick to be executed when the user press enter ? ( at this point the user will input a number in the box and press the button with the mouse - how can i make it so the user will input the number and press Enter and the same onclick function will be executed ? )
many thanks in advance.
i tried some codes but they wont work
enter code here
<div id="foot1">
<form action="" method="" name="vform">
<input type ="number" min="0" max="10000000"
placeholder="PEEM it!" value="" id="footbar" />
<div id="foot2">
<li class="foot" alt="foot" title="FOOT (ft)" onclick="runfoot()"></li>
</div>
</div>
You can use the keydown event or similar (keyup, keypress):
document.addEventListener('keydown', function(event) {
const ENTERKEY = 13;
if (event.keyCode === ENTERKEY) {
runfoot()
}
});
https://developer.mozilla.org/en-US/docs/Web/Events/keydown
Just use jQuery's click:
$(document).on("keydown", e => {
if (e.key == "Enter") {
$(".foot").click();
}
});
You can try this:
<div id="foot1">
<form action="" method="" name="vform" onsubmit="return false">
<input
type="number"
min="0"
max="10000000"
placeholder="PEEM it!"
value=""
id="footbar"
/>
<div id="foot2">
<li class="foot" alt="foot" title="FOOT (ft)" onclick="runfoot()">
</li>
</div>
</form>
</div>
<script>
document
.getElementById('footbar')
.addEventListener('keyup', function(event) {
const key = 13;
if (event.keyCode == key) {
runfoot();
}
});
</script>

How to force "enter key" to act as "tab key" using javascript?

I'm working on a site that is full of forms to be filled and I it's required that when escape button is pressed focus move to the next input control, just as pressing "tab" do.
I found code to move focus when keypressed is 13 but this need to take the ID of element to focus on
<input id="Text1" type="text" onkeydown="return noNumbers(event)" />
<input id="Text2" type="text" />
<script type="text/javascript">
function noNumbers(e) {
keynum = e.which;
if (keynum == 13)
document.getElementById("Text2").focus();
}
</script>
I need a generalized function that when key pressed code is 13 "that is enter" fire the default event of pressing 9 "that is tab", of course in Javascript
This will handle multiple input fields.
Here is the jQuery version:
http://jsfiddle.net/TnEB5/3/
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
Here is the pure javascript version:
http://jsfiddle.net/TnEB5/5/
(you probably want to get the sibling differently)
function tab(e) {
if (e.which == 13) {
e.target.nextSibling.nextSibling.focus();
e.preventDefault();
}
}
var inputs = document.getElementsByTagName('input');
for (var x = 0; x < inputs.length; x++)
{
var input = inputs[x];
input.onkeypress = tab;
}
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<input id="Text3" type="text" />
handle keypress instead and return false back to the browser:
http://jsfiddle.net/EeyTL/
<input id="Text1" type="text" />
<input id="Text2" type="text" />
<script type="text/javascript">
document.getElementById('Text1').onkeypress = function (e) {
if (e.which === 13) {
document.getElementById("Text2").focus();
return false;
}
};
</script>
You'll need to explicitly set the tabindex property of the input fields for a generic solution. Something like
<input id="Text1" type="text" tabindex="1" />
<input id="Text2" type="text" tabindex="2" />
<script type="text/javascript">
$('input').keypress(function(e){
if(e.which==13){
$("[tabindex='"+($(this).attr("tabindex")+1)+"']").focus();
e.preventDefault();
}
});
</script>
this solution uses jquery to assign the event handler for all input type elements on the page, sets focus to the element with the next highest tabindex property, and prevents the form from submitting when enter is pressed using e.preventDefault(). Here's a jfiddle
<input type="text" value="" onkeyup="doNext(this);"> a <br>
<input type="text" value="" onkeyup="doNext(this);"> b <br>
<input type="text" value="" onkeyup="doNext(this);"> c <br>
function doNext(el){
if(event.keyCode=='13'){
var nextEl = el.form.elements[el.tabIndex+1];
if (nextEl && nextEl.focus) nextEl.focus();
}
}
Althought the post is old, I hope my answer can help someone in need. I have a smilar situation:
I have a very large form for an employee scheduler application with different types of input fields. Some of the input fields are hidden sometimes and not other times. I was asked to make the enter key behave as the tab key so the users of the form could use the 10-key when creating thier employees schedule.
Here is how I solved my problem:
$(document).ready(function () {
var allInputs = $(':text:visible'); //(1)collection of all the inputs I want (not all the inputs on my form)
$(":text").on("keydown", function () {//(2)When an input field detects a keydown event
if (event.keyCode == 13) {
event.preventDefault();
var nextInput = allInputs.get(allInputs.index(this) + 1);//(3)The next input in my collection of all inputs
if (nextInput) {
nextInput.focus(); //(4)focus that next input if the input is not null
}
}
});
});
What I had to do was:
Create a collection of all the inputs I want to consider when tabbing. in my case it is text inputs that are visible.
Listen for a keydown event on the inputs in question, in my case all text field inputs
When the enter is pressed on my text input, determine what input is next to be focused.
If that input is valid, bring it into focus.
I am using this code for advancing to next input field. I hate to press TAB key. And this solution works in IE & Firefox:
<script type="text/javascript">
function tabE(obj,e){
var e=(typeof event!='undefined')?window.event:e;// IE : Moz
if(e.keyCode==13){
var ele = document.forms[0].elements;
for(var i=0;i<ele.length;i++){
var q=(i==ele.length-1)?0:i+1;// if last element : if any other
if(obj==ele[i]){ele[q].focus();break}
}
return false;
}
}
</script>
HTML Content
<form id="main">
<input name="" type="text" onkeypress="return tabE(this,event)">
<input type="submit" value="Ok">
</form>
Here is a easy solution for you.
Basically you include the enter2tab.js file and then add the enter2tab class on each object where you want enter to be treated as js.
https://github.com/AndreasGrip/enter2tab
You can obviously look at the code to understand what it does and how..
I believe using e.preventDefault(); is safer than returning false.

Canceling onkeypress event after changing focus

My users want this form to advance focus to the next field when enter is press instead of submitting the form. I've added an onkeypress handler to the test input to change the focus when enter is press.
In the code below, when keydown function changes focus, I see the cursor jump to the new textbox but then the form gets submitted as if I pressed the enter key again. I thought that by returning false in my event handler the event would not be passed on but that does not seem to be the case. I've seen this behavior in both Chrome and Firefox.
Could someone tell me what I am missing?
<form action="" name="confirmation" method="post">
<fieldset>
<div class="clearfix">
<label for="id_event_fuel_amount">Quantity:</label>
<div class="input">
<input type="text" id="event_fuel_amount_id" name="event_fuel_amount" onkeypress="keydown(event, 'event_purchase_amount_id')" />
</div>
</div>
<div class="clearfix">
<label for="id_event_purchase_amount">Sale:</label>
<div class="input">
<input type="text" id="event_purchase_amount_id" name="event_purchase_amount" />
</div>
</div>
<input type="hidden" name="state" value="3" id="id_state" />
<input type="hidden" name="time_stamp" value="2011-09-24 14:34:06" id="id_time_stamp" />
<input type="hidden" name="purchase" value="66" id="id_purchase" />
<input type="submit" value="Save"/>
</fieldset>
</form>
<script>
function keydown(e,s){
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if (code==13){
document.getElementById(s).focus();
return false;
}
}
</script>
Try
e.preventDefault();
That should prevent the event from firing the form submit.
I think this might help:
<script type="text/javascript">
document.getElementById('hello').onkeydown=function(e){
var e=window.event || e;
if (e.keyCode == 13) return false;
}
</script>
<input type="text" id="hello" />
Here is a demo: jsFiddle demo

Categories