Reputation: 3962
I have a jQuery/AJAX function that loads HTML form elements from the server. The fields on the form vary. I'd like to set focus to the 1st available input field after the load has completed. I tried:
$(':input:enabled:visible:first').focus();
but this doesn't work :( I'm not sure how I can address the input field in jQuery. I do not know the ID of the element returned.
My function looks like the below whereas the my_html variable contains a number of simple input fields, eg
<input type='text' name='test' value='prefilled' />
AJAX Function:
$.loadIDX = function (idx, position){
var url = 'URL HERE';
$.ajax({
url: url,
type: "POST",
data: {
idx:idx,
position:position
},
dataType: 'json',
success: function(data) {
if(data.status=='request'){
var my_html = '<div id="slide_in"><div id="please_enter_'+idx+'" class="please_enter">Please enter:</div><form id="cform_'+idx+'">';
// loop through json & create html input form fields
$.each(data, function(key, val) {
if(key!='status'){
my_html += val;
}
})
// close up the form
my_html += '<input class="submit_button" type="button" value="ok" onClick="postForm('+idx+','+position+')" /></form></div>';
// place the new HTML into the DIV
$('#yn_'+idx).html( my_html );
// set focus... HOW?
$(':input:enabled:visible:first').focus();
} else {
$.closeIDX(idx);
}
}
});
}
Upvotes: 2
Views: 2653
Reputation: 97717
How about
$('#yn_'+idx).html( my_html ).find('input:first').focus();
Upvotes: 3