How to stop my code putting tabs into my text boxes - javascript

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/

Related

tab key is not working as expected when using jquery change event

I had some weird result from jquery events, though I am not fully convinced whether it is a jquery issue. I hope some jquery geeks can answer this.
I had the following code snippet in my html page, to change the focus to the second input box once user enter a string of length 9 in first input box. This auto-focusing is working smoothly. But when I press tab from first input box, it is always skipping the second input box and goes to the next html element to second input box.
$("input.first").change(function (e){
var text = $(this).val();
if (text.length == 9){
$("input[id='second']").focus();
}
});
I tried putting tabindex property to html elements still it continued its misbehavior. But at the end when I changed change event to keypress event tab key started to flow as expected.
Is there anyone who could explain why this happens? Thanks for any answers.
you can add tab index to controls manually. I hope it will work.
$(function() {
var tabindex = 1;
$('input').each(function() {
if (this.type != "hidden") {
var $input = $(this);
$input.attr("tabindex", tabindex);
tabindex++;
}
});
});

Preventing double-click bug with checkbox + label combination

Note this issue may not apply to the general public, as it does not occur unless you're a fast clicker. (150-200ms/click) The reason I'm posting this issue is because my application has a form with 20+ checkboxes next to each other, and after extensive research I've found no related questions on this matter.
Here's a simplified scenario - 4 checkboxes and 4 labels, one for each checkbox id:
[CB1] Label 1
[CB2] Label 2
[CB3] Label 3
[CB4] Label 4
Assume in each case all CBs are unchecked.
Expected Behavior:
I click on the 4 CBs in rapid succession, they will all become checked. (true)
I click on the 4 Labels in rapid succession, and the corresponding CBs become checked. (only true for Chrome, but still not optimal)
Actual Behavior for case 2 on Win 7 (clicking on labels, because as you know, labels are big and style-able, and the checkboxes are tiny and OS-dependent):
(In Firefox 19) CB2 and CB4 are left unchecked, and while going down the list the word "Label" gets highlighted for Label 2 and Label 4, as if I double-clicked on them.
(In Chrome 26) All CBs get correctly checked, but while going down the list the word "Label" gets highlighted for Label 2 and Label 4, as if I double-clicked on them.
(In IE 10) CB2 and CB4 are left unchecked, but no false highlighting.
The erroneous behavior could be justified if the clicks are on the same element. In our case those are clearly unique checkboxes with different IDs and Names. So the results are wildly unexpected.
So my question is:
Is there a way to disable firing the double click event when I rapidly click on the different checkboxes, but yet still check them with fast single clicks?
The closest I've come to is the following script, which interestingly made Firefox behave like Chrome, and Chrome behave like Firefox:
jQuery(document).on('dblclick', 'input:checkbox+label', function(event){
console.log('ugly hack fired');
$(this).click();
event.preventDefault();
})
Finally got one very ugly hack that worked for all the browsers, hopefully this will help anyone else who comes across the problem:
Disable selection with css because doing it in JS is simply too inefficient:
.form_class input[type=checkbox] + label{
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-o-user-select:none;
user-select:none;
}
Prevent ALL clicking in JS, and manually do what clicking should do:
jQuery(document).on('click', '.form_class input:checkbox+label', function(event){
// Assuming label comes after checkbox
$(this).prev('input').prop("checked", function(i, val){
return !val;
});
event.preventDefault();
})
This would do it-
$("input[type='checkbox']").dblclick(function (event)
{
event.preventDefault();
});
Try this:
$(document).on('dblclick', 'input:checkbox, label', function (event) {
event.preventDefault();
// Your code goes here
})
OR
$("input:checkbox, label").dblclick(function (event) {
event.preventDefault();
// Your code goes here
});
OR
$('input:checkbox').add('label').dblclick(function (event) {
event.preventDefault();
// Your code goes here
});
I was also facing a similar issue which had me spend whole night on how this can be fixed for checkbox. I was also listening to the 'dblclick' event to prevent any action from happening on double click on a checkbox.
ex:
#(".some_class").on("dblclick",function(event){
event.preventDefault();
});
But the problem here was that it was firing the event after the action was done. So all the damage was already done.
There is a very simple way to tackle this problem that is by listening for the event 'change' instead of listening to 'click'. In this was we are triggering the event when there is a state change from check to unchecked or from unchecked to checked and not on click or double click.
#(".some_class").on("change",function(event){
event.preventDefault();
});
$('.checkbox_class').click(function(event){
if (event.ctrlKey){ event.preventDefault();
//rest of the code
seems to work

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

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" />

Preventing focus on next form element after showing alert using JQuery

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.

Categories

Resources