Cannot disable enter key on a textarea - javascript

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>

Related

Html and javascript input validation

I am trying to have my input only accept Numbers and the '.', it is working great but it doesn't allow for number pad number keys. I cant seem to find the exact answer online.
HTML
<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">
JavaScript
//prevent , and $ from being input
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
return false;
}
return true;
}
//is input numeric
function isNumeric (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode (key);
var regex = /[0-9]|\./;
if ( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Thanks for the help!
The best way I believe would be to add a class to all the inputs that only allow numbers. Then you can restrict any input that doesn't match the pattern or a number/decimal.
function numberVerfication(value) {
var pattern=/^[0-9]*(\.)?[0-9]*$/;
if (value.match(pattern) != null){
return value
}
else {
var p=/[0-9]*(\.)?[0-9]*/;
return value.match(p)[0];
}
}
$('.numbersOnly').keyup(function(e) {
e.target.value = numberVerfication(e.target.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">
Simple using REGEXP
HTML
<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">
JQUERY
$('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
JAVA SCRIPT
function numValidate(that){
that.value = that.value.replace(/[^0-9\.]/g, '');
}
<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>
Demo
function numberVerfication(value){
return value.replace(/[^0-9.\-+]/g, '');
}
$('.numbersOnly').keyup(function(e){
e.target.value=numberVerfication(e.target.value);
});

Chrome Alert Box Submits Page Even if Returning False

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>

Prevent default tabbing behavior in firefox

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

onkeyup event for checkbox

I have a simple situation here. lets face html code first =>
<form name="geoKey" method="post" action="index.php">
<fieldset class="gKey">
<legend><input type="checkbox" name="checkUncheck" id="checkUncheck"></legend>
<textarea name="txt" id="txt" cols="34" rows="5"></textarea>
</fieldset>
</form>
and here is javascript =>
function keyPress(e){
var key;
var box = document.getElementById("checkUncheck");
if (window.event){
key = event.keyCode;
} else {
key = e.which;
}
if (key==192){
(box.checked) ? box.checked=false : box.checked=true;
}
}
window.onload = function(){
document.onkeyup = keyPress;
};
so , like you see guys when it is pressed key (numbered 192) checkbox is checking if it is not checked and otherwise too (this is everything working nicely) , but here is a issue => I want that if cursor is focused on textarea and pressed that key (192) in textarea doesn't write anything . please help , thanks :)
Use onkeydown instead and prevent the default browser action by using e.preventDefault:
function keyPress(e){
var key;
var box = document.getElementById("checkUncheck");
if (window.event){
key = event.keyCode;
} else {
key = e.which;
}
if (key==192){
e.preventDefault(); // <-- prevent default action
(box.checked) ? box.checked=false : box.checked=true;
return false;
}
}
window.onload = function(){
document.onkeydown = keyPress;
};
JSFiddle demo.

HDI: Disable postback on html input box

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

Categories

Resources