Preventing focus on next form element after showing alert using JQuery - javascript

I have some text inputs which I'm validating when a user tabs to the next one. I would like the focus to stay on a problematic input after showing an alert. I can't seem to nail down the correct syntax to have JQuery do this. Instead the following code shows the alert then focuses on the next text input. How can I prevent tabbing to the next element after showing an alert?
$('input.IosOverrideTextBox').bind({
blur: function(e) {
var val = $(this).val();
if (val.length == 0) return;
var pval = parseTicks(val);
if (isNaN(pval) || pval == 0.0) {
alert("Invalid override: " + val);
return false;
}
},
focus: function() {
$(this).select();
}
});

I don't like forced focus, but can't you just focus after the blur takes place?
element.focus();
If doing that in the blur event doesn't always work (I'm not sure exactly when it fires, before or after the actual blur takes place), a redundant timeout will do, as well: setTimeout(function () { element.focus() }, 0).
But please don't do this. Heck, you should never be using alert or any kind of modal dialog for a web interface, either. How about adding a invalid class to the form field, putting a message off to the side of it, and disabling submit until all fields are valid? That's a much less invasive solution that allows me to fill out the form in whatever way is best for me, rather than whatever way is simplest for you.

You can do this with the validation plugin by default.
focusInvalid default: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Then you'd only need to have the focus event handler do your select and let the plugin handle validation.

Related

Angular - Focus event being called on lost focus

I've come across some kind of bug I believe with angular and chrome and I am not quite sure what the solution is, my angular application has custom input controls and these inputs do some stuff on focus (focus)="someEvent($event). These inputs are the username and password field so chrome stores the values. Upon loading the page again, chrome will apply the stored values, if a user clicks elsewhere on the screen (NOT on the input components), both of the input components fire the focus event.
I could understand if this happened on page load as chrome may cycle through the inputs and apply the stored values, however this happens after the first mouse click anywhere on the page.
Is there a way to interpret that these focus events were cause by the autofill feature and not the user focusing on the input manually?
I have some code on these events that do event.target.select() to select all text, and oddly enough.. the 2 inputs end up getting stuck in a focus loop. The first gets focused then the second then the first then the second forever until a user presses tab.
HTML:
<input [ngClass]="inputClass" [type]="this.type" [readOnly]="this.readonly || (this.ParentPanel && this.ParentPanel.readonly)" [ngStyle]="inputStyle" [disabled]="disabled || (this.ParentPanel && this.ParentPanel.disabled)" [(ngModel)]="value" (change)="Event_change($event)" (keyup)="Event_keyup($event)" (keydown)="Event_keydown($event)" (focus)="Event_focus($event)" maxlength="512"/>
TS:
Event_focus(event) {
console.log('focus event' , event);
if (this.selectAllOnFocus) {
setTimeout(() => { // required to work with Edge (OnFocus happens before some browser properties are set)
event.target.select();
});
}
this.OnFocus.emit(event);
}
Thanks.
I figured this out, Before the code gets called - I have it check whether or not the control is the documents activeElement.
if (this.selectAllOnFocus && this.element && this.element.nativeElement === document.activeElement) { //do rest here }
These appears to work and resolve my issue.

How to stop my code putting tabs into my text boxes

I have this piece of jQuery to detect when the cursor is inside the text box. The idea is to highlight the table row that the text box appears is.
$(".text").on("focus", function() { //do something });
The problem is that this code seems to be registering the tab key inside the text box. The cursor will still move to the next text box when I hit the tab key. However it always insert a tab space into the box as well!!
This is most unexpected and I must admit i'm a little confused by it...
Any help on this matter would be brilliant, thank you.
It seems that the alert() you are sending in the focus event is interrupting things in a strange way. You can fix this by setting a brief timeout before sending the alert; that ensures that the alert is sent AFTER the text box receives focus and the tab input has been handled.
setTimeout(function() { alert("box selected"); }, 1);
http://jsfiddle.net/5cjbcy9o/2/
Give every row a tabindex like this
var i=2;
$('tr').each($(this).attr('tabindex',i++))
A previous answer has addressed listening to the tab key, by checking the keyCode to see if it matches 9. However, the width of a tab character differs (also reliant on personal preferences), although it is either two or four spaces commonly. Therefore, you can append that white space to the value of the input text when the tab keydown event is detected.
In the following code I have opted to use four white spaces:
$(function () {
$(".text").on("focus", function () {
console.log("box selected");
}).on("keydown", function(e) {
if ((e.keyCode || e.which) == 9) {
e.preventDefault();
$(this).val($(this).val() + " ");
}
});
});
See proof-of-concept fiddle here: http://jsfiddle.net/teddyrised/5cjbcy9o/1/

Detecting when an element is about to get focus

I have an ASP.NET page with a Telerik RadEditor (rich text box). When tabbing through a page, when a user gets to the text box, focus gets set to the various toolbar icons before it goes to the textarea. I added some jQuery to one page to set the focus on the text area when tabbing out of the last cell on a form:
$('input[type=text][id*=tbCost]').keydown(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) { //If TAB key was pressed
e.preventDefault();
var editor = $('body').find("<%=RadEditor1.ClientID%>"); //get a reference to RadEditor client object
editor.setFocus(); //set the focus on the the editor
}
});
I am looking for a way to implement this functionality in the control so that it will work regardless of the page it is on. For example, in the above code, focus is only set if the user is tabbing out of the tbCost cell. I would like to be able to set the focus to the text area when a user tabs into the toolbar items.
Is there any way to detect when an element is about to get focus? I know I can see if an element has focus, but I can't think of a way to implement this functionality.
Thanks
Solution:
If anybody has this same question in the future and wants an example, here is the code I used:
$(document).ready(function () {
$('.reToolCell').focusin(function () {
var editor = $('body').find("<%=RadEditor1.ClientID%>");
editor.setFocus();
});
});
You might consider binding to a focus on the toolbar icons and redirecting focus to the text area. Although this might have unintended side effects if users are trying to tab-focus these tools in order to use them.
//on focus eventHandler for all your icons that calls a function
#('.elementtype, class or a generic way of identifying the icons'.onfocus(myFunction(this))
//the function take a parameter of your element, moves to the next sibling element and sets the focus
myFunction = (element) {
element.next().focus();
}

Event Listener valid for HTML5 forms

New on HTML5 there's an "invalid" event, to which you can add a listener:
document.addEventListener('invalid', function(e){
var element = $(e.target);
element.addClass("invalid");
element.parent().addClass("invalid");
}, true);
Please note, this event just works when submitting the form... If I style the input input:invalid { background: red }, the style is applied when the user starts typing and his input is not valid. Is that event only fired on submit? I tried adding the listener to the inputs themselves instead of the document and it didn't work.
I add a listener in order to apply a style to the input's parent... Now, when the user corrects it, it's valid again... I know there's not a "valid" event, so, how can I accomplish it?
Ok, so here's a fiddle --> http://jsfiddle.net/Osoascam/ceArQ/7/
The invalid listener seems to be only fired on submit... I just wanted to know whether there's a way to add a handler just like there is for focus. See that if you type a
Thanks in advance,
Óscar
You should use the :invalid pseudo selector and the input or the change event, to solve your problem.
$(document).bind('change', function(e){
if( $(e.target).is(':invalid') ){
$(e.target).parent().addClass('invalid');
} else {
$(e.target).parent().removeClass('invalid');
}
});
Here is a simple fiddle http://jsfiddle.net/trixta/YndYx/.
If you want to remove the error class as soon as possible you should add the error class on change and remove it on the input event (Note: input event is much better than here suggested keyup, simply because it also is triggered on paste etc., but it only works with input elements, not textarea.)
And here is a fiddle using a mixture of input and change event:
http://jsfiddle.net/trixta/jkQEX/
And if you want to have this cross browser you can simply use webshims lib to polyfill. Here is a x-browser example:
http://jsfiddle.net/trixta/RN8PA/
Since these classes are always added when a form is submit, remove the class prior validating:
$('#myForm').submit(function(){
$('.invalid', this).removeClass('invalid'); // Remove all invalid classes
$(this).removeClass('invalid'); // If the parent = form.
// Normal validation procedure.
});
Expected result:
User initiates submit
onsubmit is triggered > All invalid class names within the form are removed.
The invalid events are triggered, and the invalid classes are added when necessary
Update
Added an extra block to your fiddle, see updated fiddle: http://jsfiddle.net/ceArQ/10/. I have implemented the checkValidity() method and the validity.valid property. Now, the classes are automatically added when the input is invalid.
document.addEventListener('keyup', function(e){
var input = e.target;
if (!$.nodeName(input, 'input')) return;
input.checkValidity();
var element = $(input).parent();
if(input.validity.valid) {
element.removeClass('invalid');
element.parent().removeClass('invalid');
} else { //Remove the lines below if you don't want to automatically add
// classes when they're invalid.
element.addClass('invalid');
element.parent().removeClass('invalid');
}
});
On key-up, the validity of an input element is checked. If it's valid, the invalid class is removed from its parent.
You could bind your validation logic to the focus and blur events, or to be even more responsive, to the keyup event.
$('input').keyup(function() {
if(isValid(this)) {
$(this).removeClass('invalid').parent().removeClass('invalid');
$(this).addClass('valid').parent().addClass('invalid');
}
else {
$(this).removeClass('valid').parent().removeClass('valid');
$(this).addClass('invalid').parent().addClass('invalid');
}
});
Have you tried using :valid to give an indicator as to whether a field is valid. and having forms that are invalid just keep their default styling.
Then calling form.checkValidity() in the submit handler? (The browser should then tell the end-user which form element is not valid).

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources