开发者

Focus into a newly replaced text field using jQuery

开发者 https://www.devze.com 2023-04-04 04:06 出处:网络
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\">

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()
0

精彩评论

暂无评论...
验证码 换一张
取 消