...

View Full Version : focus isn't working



malfist
06-10-2008, 02:08 PM
This is my code, it's displayed through an AJAX request. It successfully prints malfist as the value of username, but does not focus on the username field.

Any help would be appreciated.




<script type="text/javascript">
$('#TB_ajaxContent').ready(function(){
var username = document.getElementById("username");
console.log(username);
username.value = "malfist";
username.focus();
username.select();
});

function handelLogin(e){
if(e.keyCode == 13) {
var login = document.getElementById('login');
var username = login.username.value;
var password = login.password.value;
password = md5(password);

$.post('./ajax/login2.php', {username: username, password: password}, function(data){
if(data != 1){
$('#errors').css("color", "red");
$('#errors').css("background-color", "white");
$('#errors').css("z-index", "501");
$('#errors').css("opacity", "0");
$('#errors').css("-moz-opacity", "0");
$('#errors').css("filter", "alpha(opacity=100)");
$('#errors').css("font-size", "3em");
$('#errors').css("margin-left", "auto");
$('#errors').css("margin-right", "auto");

$('#errors').text('Invalid login, please try again.');
$('#errors').effect("pulsate", {times: 5});
}else{
self.tb_remove();
window.location = ".";
}
});
}
else
return;
}
</script>
<form id="login">
<label for="username">Username </label><input type="text" maxlength="40" id="username" onKeyPress="handelLogin(event);" /><br />
<label for="password">Password &nbsp;</label><input type="password" maxlength="40" id="password" onKeyPress="handelLogin(event);" />
</form>


edit: this is outputed using a thickbox.

Philip M
06-10-2008, 05:41 PM
Try

document.login.username.focus();

var username = document.getElementById("username");
may create a conflict. Suggest that you rename the JavaScript variable to uname or whatever.

malfist
06-10-2008, 05:45 PM
document.login has no properties

malfist
06-10-2008, 05:49 PM
var uname = document.getElementById("username");
console.log(document.forms[0].username);
document.getElementById("username").value = "malfist";
document.forms[0].username.focus();


That doesn't work either. No errors, document.forms[0].username points to the right input, but no focus.

Philip M
06-11-2008, 07:57 AM
document.login has no properties


This is because the form login has an id but no name.

This could be a timing problem - the focus does actually go to the field, but only for an instant before moving to the next field. This is a bug in IE.

Try:-


function fieldFocus() {
document.forms[0].username.focus();
}
setTimeout(fieldFocus, 100); // 100ms delay


All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

malfist
06-11-2008, 01:09 PM
This


setTimeout(function(){
document.getElementById("username").focus();
}, 100);

Worked. Thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum