Focus into a newly replaced text field using jQuery
I am using jQuery to replace the HTML of a text field when it gets focus. My code looks like this:
<div id="my_field">
<%= f.text_field :first_name, :value => "Enter Name" %>
</div>
My jQuery used to replace the HTML inside my_field:
$("#my_fi开发者_StackOverfloweld")
.delegate('#my_field input', 'focus', function(e){
if($(this).attr('type') == 'text'){
$(this).parent().html('<input type="text" value="" name="..." id="name">');
}
});
Just after replacing the HTML, the newly created text box does not get the focus. What should I do to get the cursor on the text box?
Try this:
$("#my_field")
.delegate('#my_field input', 'focus', function(e){
if($(this).attr('type') == 'text'){
$(this).parent().html('<input type="text" value="" name="..." id="name">');
}
$("#name").focus();
});
Manually focus the new input
, using the no-args overload of .focus()
:
$("#my_field")
.delegate('#my_field input', 'focus', function(e){
if($(this).attr('type') == 'text'){
$(this).parent().html('<input type="text" value="" name="..." id="name">');
$("#name").focus();
}
});
Try this one:
$('<input type="text" value="" name="..." id="name">').appendTo('selector').focus()
精彩评论