I have an input box that I don't want postback to occur on someone striking the enter key
I want the javascript event to take place instead.
<input
type="text"
id="addressInput"
onkeydown="inputenter()"
autopostback="false"/>
function inputenter() {
if (event.keyCode == 13) {
seachLocations();
return false;
}
else {
return false;
}
}
Just return false form JS function, add return false; at the end of function.
or <input type="text"
id="addressInput"
onkeydown ="return (event.keyCode!=13)"
autopostback="false"/>
UPDATE:
How about this..?
<asp:TextBox ID="TextBox1" runat="server"
onkeydown="return CallEnterKeyFunc(event.keyCode);">
</asp:TextBox>
<script type="text/javascript">
function CallEnterKeyFunc(key) {
if (key == 13) { //for FF, i think you have to use evt.which
//enter key press
seachLocations();
return false;
}
else
return true;
}
function seachLocations() {
//your code
alert("hello");
}
</script>
Special thanks to: http://www.beansoftware.com/ASP.NET-Tutorials/Accept-Enter-Key.aspx
<input type="text" id="addressInput" onkeydown="if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
searchLocations();
}" />
Related
why doesn't my function return an alert given this particular code?
function searchString() {
if (event.keyCode == alert("Success!"); }
}
Here is my HTML code:
<input type="text" id="searchString" name="searchString" onkeydown="searchString();"/>
You need to pass the event argument in your function. Otherwise event is undefined when you try to invoke the keyCode method:
function searchString(event) {
if(event.keyCode == 13) {
alert("Success!");
}
}
document.querySelector('input').addEventListener('keyup', searchString);
function searchString(event) {
if (event.keyCode == 13) {
alert("Success!");
}
}
<p>Press the <b>enter</b> key in the input below see your alert</p>
<input type="text" />
You can do it with pure javascript:
const search = document.getElementById('searchString');
search.addEventListener('keydown', (e) => {
if (e.keyCode === 13) {
// your code here
}
}
Note: 13 is the key code for the enter
You need to ensure that the actual event is being passed as an argument... otherwise, it will be unrecognised within the function. To see which code is tied to which key, please try the following.
function check(event)
{
var keycode = event.keyCode;
alert(keycode);
}
And then ...
<input type="text" id="check" name="check" onkeydown="check();">
The return key is tied with '13'. So if you just want to do something when it is pressed, do the following.
function searchString(event)
{
if(event.keyCode === 13) {
alert("return key was pressed");
// do something ....
}
}
And the html code should be something like the following.
<input type="text" id="searchString" name="searchString" onkeydown="searchString();">
Please note that I have used '===' instead of '=='. It is now the recommended practise. Also, note that the forward slash at the end of input is not necessary.
In my application I have a textbox to search for items. In this textbox I want the user to have to enter at least 2 characters before searching. If there's less than 2 characters then I want to display a simple alert box telling the user to enter at least 2 characters. On my text box code looks like:
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
alert('Please ENter at Least 2 Characters');
//return false;
obj.select();
obj.focus();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" name="txtSearch" />
In my javascript the function on every keystroke from the user, it checks the keyCode being pressed looking for the 'Enter' input. If the user presses 'Enter' and the number of characters in the textbox is less than 2 then it should alert the user and return false. But regardless the form is still submitted when the user presses 'Enter'.I also noticed it doesn't hit the 'doEnterKey' function it just submits the form. Any help or suggestions is appreciated.
In Internet Explorer everything works as should, the javascript code stops wait for input from the user then continues, returning false. However in chrome the alert box is displayed it and it still submits the form, almost as if it's not returning the false back to the element.
Pass the event object in the call and on ENTER prevent event default.
I used the keypress event and tested on IE, FF and Chrome.
Now the alert message on form submit will not happen because the ENTER is prevented.
function checkSearchLen(event, obj, defaultEnterButton) {
event = event || window.event;
if (obj.value == 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
event.preventDefault();
return false;
} else
doEnterKey(defaultEnterButton);
}
function doEnterKey(s) {
if (event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
document.getElementById(s).click();
}
}
<form action="http://www.google.com" onsubmit="alert('submit');">
<input class="searchtext" id="txtSearch" value="Search" onfocus="this.value = '';this.style.color='black';this.style.fontStyle='normal';" onkeypress="checkSearchLen(event, this,'MenuBar_imgSearchGo');" name="txtSearch" />
</form>
The best method to deal with this kind of problems is by using Jquery...just a few lines of Jquery code is capable of doing what you did in the entire program!
Another alternate answer is to do checking in form submit event and cancel that submit event based on invalid input. This will prevent page post back. Actually, this is the same approach that ASP.Net framework takes when a page has ASP.Net validators in it with client-side validation turned on.
Also, there is no need to cancel the event in doEnterKey, so I have commented two lines in that function.
The following code will work as I have tested on my side. There are two aspects to the logic being used:
A global variable stopSubmit decides if form submit event will be canceled or not. If this variable is true then form submit event will cancel.
The original form submit event code of the form is being pre-pended with our custom JavaScript that will return a false in case the form submit needs to be canceled. This is happening when body loads for the page i.e. body's onload event calls setFormSubmit to modify existing form submit code. If everything was valid, then original form submit code executes without issues and page posts back.
<body onload="setFormSubmit()">
<form id="form1" runat="server">
<asp:Label ID="label1" runat="server"></asp:Label>
<div>
First name:
<input type="text" name="FirstName" value="Mickey" /><br />
Last name:
<input type="text" name="LastName" value="Mouse" /><br />
<input type="submit" value="Submit" />
<input type="text" onkeydown="checkSearchLen(this,'MenuBar_imgSearchGo');" />
<input type="submit" value="Submit" id="MenuBar_imgSearchGo"/>
</div>
<script>
var stopSubmit = false;
function setFormSubmit() {
document.forms[0].setAttribute("onsubmit", " var stopPostback = StopPostback(); if(stopPostback === true) { return false; } " + (document.forms[0].onsubmit === null ? "" : document.forms[0].onsubmit));
}
function checkSearchLen(obj, defaultEnterButton) {
if (obj.value === 'Search') obj.value = '';
if (obj.value.length < 2 && event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
stopSubmit = true;
alert('Please ENter at Least 2 Characters');
obj.select();
obj.focus();
return false;
} else {
stopSubmit = false;
doEnterKey(defaultEnterButton);
}
}
function doEnterKey(s) {
if (event.keyCode == 13) {
//event.returnValue = false;
//event.cancel = true;
document.getElementById(s).click();
}
}
function StopPostback() {
if (stopSubmit === true) {
stopSubmit = false;
return true;
}
return false;
}
</script>
</form>
I have the following code and I need to convert it to Angular Js..also I'd like to stop the user from entering a space only at the start (can't input space bar before any text)
<input type="text" name="firstname" runat="server" onkeypress="return AvoidSpace()">
function AvoidSpace() {
var x=document.forms["firs`enter code here`tname"].value;
if (event.keyCode == 32 ) {
event.returnValue = false;
return false;
}
}
in order to filter space key press you can use the pattern feature of input type=text.
html5 only: https://www.w3.org/wiki/HTML/Elements/input/text
angularjs: https://docs.angularjs.org/api/ng/input/input[text]
<input ng-pattern="[^\s+]" type="text" name="firstname">
update:
you can use the directive ngKeypress:
<input ng-pattern="[^\s+]" type="text" name="firstname" ng-keyup="checkinput($event)">
controller:
$scope.checkinput = function(keyevt){
if (keyevt.keyCode === 32 ) {
keyevt.returnValue = false;
return false;
}
}
<input type="text" name="firstname" runat="server" ng-keypress="AvoidSpace()">
function in controller
$scope.AvoidSpace = function AvoidSpace() {
var x=document.forms["firs`enter code here`tname"].value;
if (event.keyCode == 32 ) {
event.returnValue = false;
return false;
}
}
I have few input fields to update.When press tab key I need move focus to the next field only after success of some validation of the current field. If fails then remain in the same field.
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
return fieldFocus(e, nxtFld);
});
This works fine in IE and Chrome. But in firefox the default focus always fires before the validation. Please help me on this to prevent that default behavior of the firefox.
---- Edited Code related to #Faizul Hasan's code ----
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
var answer = confirm('Are you sure?')
if(answer)
return true;
else{
// need to stop cursor focus to the next field
e.stopPropagation();
e.preventDefault();
}
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
This is where Im getting the real problem, before user confirms the focus moves to next field in firefox. But in IE and Chrome its working fine.
Try something like this. This works fine in Chrome and Firefox too.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script>
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
</script>
</head>
<body>
<input type="text" id="first-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="second-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="third-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fourth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="fifth-field" onkeydown="fieldFocus(event, this);" />
<input type="text" id="sixth-field" onkeydown="fieldFocus(event, this);" />
</body>
Please note this is a sample code for your reference since the way you fire the function is not mentioned in your code. You can use jQuery to easily call the function for keydown event instead of calling it for all input element like onkeydown = functionName(<params>). Hope this would help you.
Updated: Same code but jQuery integrated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="jquery-1.8.2.js"></script>
<script>
$(document).ready(function(){
$('.input-element').each(function(index, value){
$(value).keydown(function(event){
fieldFocus(event, this);
});
});
function fieldFocus(e, obj){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
// do validate
if (0 !== obj.value.length){
return true;
}
else{
e.stopPropagation();
e.preventDefault();
}
}
return false;
}
});
</script>
</head>
<body>
<input type="text" id="first-field" class="input-element" />
<input type="text" id="second-field" class="input-element" />
<input type="text" id="third-field" class="input-element" />
<input type="text" id="fourth-field" class="input-element" />
<input type="text" id="fifth-field" class="input-element" />
<input type="text" id="sixth-field" class="input-element" />
</body>
</html>
After few workouts I found something with the Firefox which causes the problem. It is the 'keypress' event.
The 'keypress' event still fires when apply preventdefault() to keydown but only in Firefox.
So I handled the 'keypress' as below and solved my problem.
Hope this will help many others.
var browsFix = false;
function fieldFocus(e, nxFld){
var key;
if (window.event) key = e.keyCode;
else if (e.which) key = e.which;
if (!e.shiftKey && key === 9) {
browsFix = true;
e.stopPropagation();
e.preventDefault();
// do validate {}
if (success)
$(nxFld).focus(); //set the focus to the next fld
else
// remain in the same field
}
return false;
}
$(currFld).bind("keydown",function(e) {
browsFix = false;
return fieldFocus(e, nxtFld);
});
$(currFld).bind("keypress",function(e) {
if (browsFix)
return false;
});
hi guys
i am trying to disable enter key from submitting the form in a textarea
using the following function:
function noenter() {
return !(window.event && window.event.keyCode == 13);
}
html code:
<form:form modelAttribute="myObject" method="post" action="${myUrl}">
<form:textarea path="name" class="new_obj submits_on_return" cols="40" rows="3" onkeypress="return noenter()"></form:textarea>
but it doesn't work at all, it always submits, any ideas why ?
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13)
return false;
else
return true;
}
</script>