focus() does not seem to work after onblur() - javascript

I have a list of input fields and when I tab through them I want to loop back to the first one, but it doesn't seem to work.
Here is my HTML
<form id="form">
<input id="mon" type="text"/> Month<br>
<input id="day" type="text"/> Day<br>
<input id="num" type="text"/> Year<br>
<input id="amt" type="text"/> Amount<br>
</form>
and my javascript
window.onload=function(){
$('mon').focus();
$('amt').onblur=function(){
//Process the input fields
$('mon').focus();
}
}
function $(a){return document.getElementById(a)}

I think your onblur event handler is being called before the default handler, causing focus to shift first to input 'mon', then to whatever the browser thinks should be in focus next. Try using the onkeypress event. e.g.
window.onload=function(){
$('mon').focus();
$('amt').onkeydown = function(e) {
//check for IE weirdness
if (e === undefined && event !== undefined)
e = event;
if (e.keyCode == 9) {
$('mon').focus();
return false;
}
}
}
function $(a){return document.getElementById(a)}
Edit: onkeydown actually seems to work in more browsers
Edit 2: added IE case. IE doesn't always pass the event as an argument

For the cursor to appear on the first input box, you need to assign the value of the input box to itself (hack). Also you need to "return false" to stop the event propagation. The modified blur function is below,
<input id="mon" type="text" onfocus="this.value=this.value;" />
$('amt').onblur = function(){ $('mon').focus(); return false; }

Take a look at this fiddle. I think this is what you want to achieve.
http://jsfiddle.net/CucuIonel/7Fpu3/7/

Related

jquery focus first form element on tab of final

I am trying to get the cursor to jump to focus on the first element of the form. For some reason it keeps getting focus on the 2nd element instead of the first. I did just a simple form.
<form>
<input type="text">
<input type="text">
<input type="text">
<input type="submit" value="Submit">
</form>
$('form').children().keydown(function(e) {
if (e.keyCode == 9 || e.which == 9) {
if ($(this).is(':last-child')) {
$(this).parent().children().first().focus();
}
}
})
Problem
Fiddle
See console logs
when you press tab on last element it focus the 1st element and then perform tab operation so it goes to 2nd element .
Solution
Use event.preventdefault() or return false to stop tab operation .
Working Demo or Working Demo
if ($(this).is(':last-child')) {
$(this).parent().children().first().focus();
e.preventDefault(); // or return false;
}

Tab keyascii in javascript doesn't work

for example I've 3 elements in my HTML code for text input.
<input type="text" name="txt1" />
<input type="text" name="txt2" />
<input type="text" name="txt3" />
At first load, I set by js to focus in txt1.
My question is, How I can manipulate keyascii when I pressing tab from txt1 to txt3 ?
The fact, I've added some js code with jquery to do that, but doesn't work! It's always focused to txt2. This is my js code:
$('input[name="txt1"]').keyup(function(e){
if((e.keyWhich || e.keyCode) == 9){
$('input[name="txt3"]').focus();
}
});
Listen for keydown and use e.preventDefault() to prevent the default behaviour.
The default behaviour for pressing tab is executed before the keyup event is being fired. That's why you have to use keydown instead.
$('input[name="txt1"]').keydown(function(e){
if((e.keyWhich || e.keyCode) == 9){
e.preventDefault();
$('input[name="txt3"]').focus();
}
});
See this Fiddle
You should listen for keydown instead and be using e.preventDefault()
Example:
$('input[name="txt1"]').keydown(function(e){
if((e.keyWhich || e.keyCode) == 9) {
e.preventDefault();
$('input[name="txt3"]').focus();
}
});
See on JSFiddle
Documentation of preventDefault

jquery each for all text boxes

I am using following script to bind a keypress event on each textbox so that on reaching the maxlength, focus will switch to next input field. Passing classname as the prarameters to the function.
function autoFocusPhoneFields(txtbox1ID,txtbox2ID) {
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
$(this).bind('keypress', function(){
if(this.value.length == $(this).attr('maxlength')) {
$(this).next('input').focus();
}
});
});
}
$(document).ready(function(){
autoFocusPhoneFields('mobileprefix','mobilecode');
});
As i have mentioned two different input ..it is runnign fine. Butis there any way around so that it will get the classnames and runs through each input box to attach keypress event.
If I understand you correctly, you want to attach the same event handler to every input field? Just use the selector:
$(':text')
(for all input type="text") fields.
So just change
$('input.'+txtbox1ID+', input.'+txtbox2ID+'').each(function() {
to:
$(':text').each(function() {
If I get you correctly you just need to use type selector for input. You can also get rid of calling each to iterate thru inputs since binding event to multiply elements interates via them. So you can change your code into something like following:
var autoFocusPhoneFields = function () {
$('input:text').keypress(function() {
if(this.value.length == $(this).attr('maxlength'))
$(this).next('input').focus();
});
}
$(autoFocusPhoneFields);
This works fine.
HTML
<input id="one" class="inp" maxlength="5" />
<input id="two" class="inp" maxlength="3" />
<input id="three" class="inp" maxlength="2" />
JS Part
$(function(){
var onpress = function(){
var val = $(this).val();
var next_input = $(this).next('input');
var mx = $(this).attr('maxlength');
try {
mx = Number(mx);
if (next_input.length >= 1 && val.length >= mx){
next_input.focus();
}
} catch(x){}
}
$('input.inp').bind('keypress', onpress);
});

jquery: event for simulating live typing

Part 1:
Is there any event I can use to get a callback when the user 'change' the input field. My definition of change is to simulate the following effect. say, I want to update a label while the user typing in the input box. I tried jquery "change" event. It works, but doesn't have the live effect. Once the input field is updated, I have to click on somewhere in the screen to update the label.
Part 2:
well, if this is not a good idea, I may prevent the form being submitted on enter key. Not sure about a good way to do it either. Quick search found this answer.
<form action="" method="post" onsubmit="return false;">
not tested yet, but hopefully the submit button may still works.
EDIT: tested, and onsubmit="return false;" prevents even the submit button.
thanks,
bsr.
This should do it:
input.bind('keydown keypress', function() {
setTimeout(function() {
label.text(input.val());
}, 0);
});
Live demo: http://jsfiddle.net/simevidas/qTBxv/
Part 1
You can just update it every keyUp, but I would suggest you at least wait 1 second after the user finishes typing.
var timer;
var changeTxt = function(){
// Change label text here.
};
$("#myInput").keyup(function(){
clearTimeout(timer);
timer = setTimeout(changeTxt, 1000);
});
Part 2
That example you posted stops a form from submitting. Is that your goal?
EDIT:
I think you are trying to control the form's submission?
$("#myForm").submit(function(){
if(/* Your condition here */){
return false;
//Only if your condition is true, stop form submission
}
});
Did you try out the keydown or keypress event?
I would prefer a combination of both, form and field validation:
Find working sample here: http://jsfiddle.net/ezmilhouse/9mNc4/1/
your html:
<form method="post" action="post.php">
<input type="text" name="" value="" />
<label>Name</label>
<div></div>
</form>
your js:
// prevent form from being posted empty
$('form').live('submit', function(evt){
if ( $('input', this).val() === "" ) {
evt.preventDefault();
alert('Field is required!');
}
});
// validate form field on the fly
var min = 3;
$('input').live('keyup change', function(){
if ($(this).val().length < min) {
$('div').html('<span class="invalid">min. 3 characters.</span>');
} else {
$('div').html('<span class="valid">ok!</span>');
}
});
there is something called oninput that you can use.
<form oninput="xx.value=aa.value">
<input type="text" name="aa" value="">
<output name="xx" for="aa"> </output>
</form>

Problem with giving focus to first element inside a container

I am just trying to cycle the focus between elements inside a particular element when the tab key is pressed. What I want to do is not to set focus to any element which is not a descendant of an element when tab is pressed from the last control inside the element. At that time the focus must be set to the first input element inside the container.
I have done a sample and it its not working, and I am unable to figure out the issue.
Sample can be found here
The complete code is
Script
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 )
{
var firstElem = $(":input:first","#div1");
firstElem.focus();
}
});
});
CSS
input.red { width: 200px; border: solid 1px red; }
input { width: 200px; }
HTML
<input type="text" class="red" />
<div id="div1">
<input type="text" id="txt1" />
<select id="sel1">
<option>1</option>
</select>
<input type="text" id="txt2" />
</div>
Any help would be appreciated.
Thanks
Edit
Thanks everyone. Problem solved. It was the lack of a return false; statement in the keydown event.
Try Keypress instead of Keydown
Also return false so that the keypress normal handling is cancelled.
What appears to be happening is that you are moving the focus then the tab happens, moving it to the select. You need to setfocus, then return false so that the regular tab is cancelled.
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 )
{
var firstElem = $(":input:first","#div1");
firstElem.focus();
return false;
}
});
});
Your example is not working because you are not stopping the keystroke, you set the focus on the first element, and then the tab key is sent, which causes the focus to be changed to the second element.
Try:
$(function(){
$(":input:last","#div1").bind("keydown", function(e){
if ( e.keyCode === 9 ) {
var firstElem = $(":input:first","#div1");
firstElem.focus();
e.preventDefault(); // or return false;
}
});
});
Check the above example here.
Can you not just use the tabindex attribute in the html?
If your page is dynamic it might be easier to set this attribute using JS rather than capturing the keypress etc.

Categories