How to keep focus after validation when use tab key - javascript

I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?
function validation(id) {
var obj = document.getElementById(id);
obj.value = obj.value.toUpperCase();
if(value == "") {
obj.focus();
obj.select();
}
}

You can add an event on 'blur'. There after check for the keyCode. For tab key it is 0. Using an setTimeout since the current element will loss focus as soon as the is a onblur event. Therefore providing a sufficient time gap before focusing back on the element
var obj = document.getElementById('inputField');
obj.addEventListener('blur', function(event) {
if (event.which === 0 && event.target.value == '') {
setTimeout(function(){
event.target.focus();
},1000)
}
})
<input id='inputField' onchange='validation(this.id)'>

Adding the validation with button instead onchange event in input box .And if(value == "") value is a undefined so change the if condition with !Obj.value.trim() its catch the false condition .trim() used for remove unwanted space
Updated
use with blur
event instead of onchange .Its only allow to next input only present input was filled.
function validation(obj) {
obj.value = obj.value.toUpperCase();
if(!obj.value.trim()) {
obj.focus();
//obj.select();
}
}
<input id="input" type="text" onblur="validation(this,event)">
<input id="input" type="text" onblur="validation(this,event)">

Related

Check if text is selected on keydown event

I have a scenario where i prevent user from entering 2nd numeric after a decimal.I have my code on keydown event.
Below is my code:
$scope.Inputkeydown = function (event, value) {
if (event.keyCode != 8) {
if (value != null && value != undefined && value != "") {
var regex = /^\d*\.\d$/; //this regex passes only decimal numbers with one digit after decimal
if (regex.test(value)) {
event.preventDefault();
}
}
}
};
Now the trouble is if user selects on the text(say 50.0) in the textbox and say presses 5 at that time it is getting prevented too, as in the textbox value is 50.0 and regex allows it go and it is getting prevented from being typed in.
Can i check on keydown if text is being copied?? or is there any other way around?
Instead of preventing the user from entering it, you could just remove it after keypress:
function filterDecimals(inp) {
return inp.replace(/^(\d*\.\d)\d*$/g, '$1');
}
Or, if you want to remove everything after it, replace the second \d* with .*
EDIT (example of usage)
This function takes the text as input and returns the new filtered text. To use this, just attach an event handler on keypress like so:
<input type="text" id="filteredbox">
<script>
var txt = document.getElementById("filteredbox");
// on keyup event (you can change to keypress if you want, but this is more logical here
txt.addEventListener("keyup", function(){
// sets value of txt to the returned data from filterDecimals()
// if statement: only filters it if necessary; this eliminates the "selected text" issue you mentioned
if (this.value !== filterDecimals(this.value)) {
this.value = filterDecimals(this.value);
}
});
</script>

I can't stop the alert method in Chrome

I have an input text and a button for checking the input text value.
When the web page is loaded, the input text has the focus and this value is empty by default.
So when you put the focus outside the input text (onblur), the check_input_value(event) function executes the alert("Your input value must not empty") one time when the input text value is empty.
This works perfectly in Firefox. But in Chrome, this alert is executed indefinitely instead of one time.
Here the code (you can try it (try it with Chrome) at https://jsfiddle.net/fcg86gyb/ ) :
<input type="text" id="input_text"> <input type="button" value="Check input value" onclick="check_input_value(event);">
<script type="text/javascript">
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function
to check input text value :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
check_input_value(event);
}
, false
);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.focus();
return false;
}
}
</script>
So how to execute one time the alert instead of indefinitely in Chrome?
The chrome execute indefinitely instead of one time because your function always return the focus to the input text and always you change the focus your function will be call. In Firefox works well because the input text does not receive the focus in the end of the javascript function.
If you remove input_text.focus(); it is going to work.
Thanks for the link to jsfiddle. I tried working on it and found that the input_text.focus() was getting called recursively.
I commented that and it worked. I think you should call the input_text.focus() somewhere outside where the call may not be recursive.
This is the link where I tried: https://jsfiddle.net/fcg86gyb/1/
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
check_input_value(event);
}
, false
);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
//input_text.focus();
return false;
}
}
If you need to maintain the focus on the textbox after showing the alert box only once, you can make use of temporary variable as I stated in the comment and you can achieve the same as follows:
//Get the input text element :
input_text = document.getElementById("input_text");
//Put focus in input text :
input_text.focus();
var temp = 0;
/*Add event listener in the input text element.
On blur, if your input value is empty, then execute check_input_value(event) function :
*/
input_text.addEventListener('blur',
function(event)
{
var event = window.event || event;
if(temp == 0)
{
check_input_value(event);
}
else
{
button_focus();
}
}
, false);
//Function for checking input text value :
//if the input value is empty, display alert "Your input value must not empty", and put focus in input text.
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.focus();
temp = 1;
return false;
}
}
function button_focus()
{
if(input_text.value == "")
{
input_text.focus();
}
temp = 0;
return false;
}
Hope it helps.
This seems to be a bug in Chrome 52 (discussed here). A workaround that came up was to remove the blur event and reattach it in a timeout:
if(input_text.value == "")
{
alert("Your input value must not empty");
var tmpBlur = input_text.blur;
input_text.blur = null;
setTimeout(function() {
input_text.focus();
input_text.blur = tmpBlur;
}, 0);
return false;
}
https://jsfiddle.net/wpys5x75/3/
EDIT:
However it looks like you still get the same infinite loop when you click outside the window. Another work around would be to assign a different value and then reassign the value in the timeout:
if(input_text.value == "")
{
alert("Your input value must not empty");
input_text.value = ' ';
setTimeout(function() {
input_text.focus();
input_text.value = '';
}, 0);
return false;
}
https://jsfiddle.net/wpys5x75/5/
I too faced same issue; I solved it by calling the focus method using setTimeout method.
Code goes as below:
function check_input_value(event)
{
var event = window.event || event;
if(input_text.value == "")
{
alert("Your input value must not empty");
setTimeout (function(){input_text.focus()}, 0);
return false;
}
}

Prevent user from typing in input at max value

I'd like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:
$('.equipCatValidation').keyup(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
To confirm I want the value not the string length, and it can't be above 100.
However this is not preventing further input in the field. What am I missing.
Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.
You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.
<input class="equipCatValidation" type="number" />
When using input type="number", change also needs to be on the event list.
$('.equipCatValidation').on('keydown keyup change', function(e){
if ($(this).val() > 100
&& e.keyCode !== 46 // keycode for delete
&& e.keyCode !== 8 // keycode for backspace
) {
e.preventDefault();
$(this).val(100);
}
});
http://jsfiddle.net/c8Lsvzdk/
Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,
HTML :
<input id="inputBox" type="text" />
jQuery :
$("#inputBox").on("keypress", function(e){
var currentValue = String.fromCharCode(e.which);
var finalValue = $(this).val() + currentValue;
if(finalValue > 100){
e.preventDefault();
}
});
jsFiddle
Maybe keydown instead of keyup?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('.equipCatValidation').keydown(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
})
</script>
</head>
<body>
<input type="text" class="equipCatValidation">
</body>
</html>
EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.
It is bad UI to disable the input if a user inputs a bad value. I'm assuming you simply want to put a max value that the user cannot go over. If so, you can either clamp the value, or use the max attribute in your markup:
<form>
<input type='number' max='100'>
</form>
If you input an invalid value, the input will turn red, and you cannot submit the form.
<input class="equipCatValidation" />
var maxValue = 100;
jquery
$('.equipCatValidation').on('keypress', function(e){
/* preventing set value when it doesn't pass conditions*/
e.preventDefault();
var input = $(this);
var value = Number(input.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
/* if value < maxValue => set new input value
in this way we don't allow input multi 0 */
$element.val(value);
}
});
vanilla js
document.querySelector(".equipCatValidation")
.addEventListener("keypress", function(e) {
e.preventDefault();
var input = e.target;
var value = Number(input.value);
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
input.value = value;
}
});
example
addition to the this answer
$('.equipCatValidation').on('keypress', function(e){
var $element = $(this);
var value = Number($element.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
}
if (value > 100) {
return false;
}
});
Here's a solution for those using modern vanilla Javascript:
Just snap the value back down to the max when the user focuses away from the input.
You would set the input to a number type and the max value
<input type="number" max="100">
and then add a function to the onblur method of the element
document.querySelector('input[max]').onblur = function (event) {
// If the value is less than the max then stop
if (Number(event.target.value) < event.target.max) return
// Snap the value to the max
event.target.value = event.target.max
}
You can also use oninput instead of onblur but that may cause the user to have to fight the input in certain situations.
Example

Prevent jumping to the second row after pressing Enter on a text area

I have a <textarea> that onkeypress ('Enter') sends a message in a live chat. The problem is that after pressing first time "Enter", the textarea field starts from the second input row.
How do I make the field reset or not taking "Enter" as a next row value?
Code:
<textarea disabled = "enabled"
onblur = "stopTyping();"
onfocus = "playTitleFlag=false;
window.title='';"
onkeypress = "tryToSend(event);"
id = "chatmsg"
rows = "1"
cols = "1"
class = "chatmsg"></textarea>
And the onkeypress function:
function tryToSend(event) {
var key = event.keyCode;
if (key == "13") {
sendMsg();
return;
}
var msg = document.getElementById("chatmsg").value;
if (trim(msg) != "") {
typing();
}
else {
stopTyping();
}
}
To cancel the default behaviour you should use return false;
see What's the effect of adding 'return false' to a click event listener?
To reset a textarea simply set its value to "". document.getElementById(f).value = "";
P.S
Note that event.keyCode return an integer

Prevent form submission with enter key

I just wrote this nifty little function which works on the form itself...
$("#form").keypress(function(e) {
if (e.which == 13) {
var tagName = e.target.tagName.toLowerCase();
if (tagName !== "textarea") {
return false;
}
}
});
In my logic I want to accept carriage returns during the input of a textarea. Also, it would be an added bonus to replace the enter key behavior of input fields with behavior to tab to the next input field (as if the tab key was pressed). Does anyone know of a way to use the event propagation model to correctly fire the enter key on the appropriate element, but prevent form submitting on its press?
You can mimic the tab key press instead of enter on the inputs like this:
//Press Enter in INPUT moves cursor to next INPUT
$('#form').find('.input').keypress(function(e){
if ( e.which == 13 ) // Enter key = keycode 13
{
$(this).next().focus(); //Use whatever selector necessary to focus the 'next' input
return false;
}
});
You will obviously need to figure out what selector(s) are necessary to focus on the next input when Enter is pressed.
Note that single input forms always get submitted when the enter key is pressed. The only way to prevent this from happening is this:
<form action="/search.php" method="get">
<input type="text" name="keyword" />
<input type="text" style="display: none;" />
</form>
Here is a modified version of my function. It does the following:
Prevents the enter key from working
on any element of the form other
than the textarea, button, submit.
The enter key now acts like a tab.
preventDefault(), stopPropagation() being invoked on the element is fine, but invoked on the form seems to stop the event from ever getting to the element.
So my workaround is to check the element type, if the type is not a textarea (enters permitted), or button/submit (enter = click) then we just tab to the next thing.
Invoking .next() on the element is not useful because the other elements might not be simple siblings, however since DOM pretty much garantees order when selecting so all is well.
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function(){
if (this === e.target) {
focusNext = true;
}
else if (focusNext){
$(this).focus();
return false;
}
});
return false;
}
}
}
From a usability point of view, changing the enter behaviour to mimic a tab is a very bad idea. Users are used to using the enter key to submit a form. That's how the internet works. You should not break this.
The post Enter Key as the Default Button describes how to set the default behaviour for enter key press. However, sometimes, you need to disable form submission on Enter Key press. If you want to prevent it completely, you need to use OnKeyPress handler on tag of your page.
<body OnKeyPress="return disableKeyPress(event)">
The javascript code should be:
<script language="JavaScript">
function disableEnterKey(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
}
</script>
If you want to disable form submission when enter key is pressed in an input field, you must use the function above on the OnKeyPress handler of the input field as follows:
<input type="text" name="txtInput" onKeyPress="return disableEnterKey(event)">
Source: http://www.bloggingdeveloper.com/post/Disable-Form-Submit-on-Enter-Key-Press.aspx
Set trigger for both the form and the inputs, but when the input events are triggered, stop the propagation to the form by calling the stopPropagation method.
By the way, IMHO, it's not a great thing to change default behaviors to anything any average user is used to - that's what make them angry when using your system. But if you insist, then the stopPropagation method is the way to go.
In my case i wanted to prevent it only in a dinamically created field, and activate some other button, so it was a little bit diferent.
$(document).on( 'keypress', '.input_class', function (e) {
if (e.charCode==13) {
$(this).parent('.container').children('.button_class').trigger('click');
return false;
}
});
In this case it will catch the enter key on all input's with that class, and will trigger the button next to them, and also prevent the primary form to be submited.
Note that the input and the button have to be in the same container.
The previous solutions weren't working for me, but I did find a solution.
This waits for any keypress, test which match 13, and returns false if so.
in the <HEAD>
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.which == 13) && (node.type == "text")) {
return false;
}
}
document.onkeypress = stopRKey;
I prefer the solution of #Dmitriy Likhten, yet:
it only worked when I changed the code a bit:
[...] else
{
if (focusNext){
$(this).focus();
return false; } //
}
Otherwise the script didn't work.
Using Firefox 48.0.2
I modified Dmitriy Likhten's answer a bit, works good. Included how to reference the function to the event. note that you don't include () or it will execute. We're just passing a reference.
$(document).ready(function () {
$("#item-form").keypress(preventEnterSubmit);
});
function preventEnterSubmit(e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
var focusNext = false;
$(this).find(":input:visible:not([disabled],[readonly]), a").each(function () {
if (this === e.target) {
focusNext = true;
} else {
if (focusNext) {
$(this).focus();
return false;
}
}
});
return false;
}
}
}

Categories

Resources