I’m having an issue adding focus() to an input that is dynamically created with jquery. I’m still learning, so I’ve mixed in traditional js with my jquery code because it’s easier for me to understand. Anyhow document.getElementById(name).style.backgroundColor=“#72A4D2”; successfully changes the background of the input ID, but document.getElementById(name).focus(); does nothing. I know that this is the correct code because if I hard code an input into the form (which you can see I’ve commented out below, such as document.getElementById(‘password’).focus(); it refocuses successfully on that input. Thus I’m stumped.
Anyone know how to deal with this issue?
JS:
$(function() {
var i = $('input').size() + 1;
$('a.add').click(function() {
$('<p>Username ' + i + ': <input type="text" id="user' + i + '" name="user' + i + '" onblur="javascript:checkl(this.name, this.value);"></p>').animate({ opacity: "show" }, "slow").appendTo('#inputs');
i++;
});
});
function checkl(name, value){
var errors=new Array();
var x;
var msg = "There were some problems...\
";
if (value==="") {
errors['blank'] = "Field must not be blank";
}
for (x in errors)
{
msg += "\
"+errors[x];
}
if (!(x==undefined)){
alert(msg);
document.getElementById(name).style.backgroundColor="#72A4D2"; //works, changed input background successfully
document.getElementById(name).focus(); // does NOT work, no focus
// document.getElementById('password').focus(); // successfully refocuses on hard coded 'password' input
}else{
document.getElementById(name).style.backgroundColor="";
}
}
@SgtLegend - I wouldn’t want to focus immediately after the onblur because everytime a user input valid data, that would just refocus on the field, even if everything was good. Or atleast I think that’d be the case.
Apparently it was only a firefox issue, as IE & Chrome rendered correctly. Someone helped me out in another post and so if anyone else finds themselved with this firefox issue, it works when replacing
document.getElementById(name).focus(); // does NOT work, no focus
with
setTimeout("document.getElementById('" + objField.id + "').focus()", 10); // works great in all browsers