开发者

jQuery: Textfield loses focus on unwrap()

开发者 https://www.devze.com 2023-01-28 15:15 出处:网络
I\'ve got a text field that is wrapped in an error div when the user either submits or focuses off an invalid input. I would like to remove the wrapper if the user corrects his mistake, however, the u

I've got a text field that is wrapped in an error div when the user either submits or focuses off an invalid input. I would like to remove the wrapper if the user corrects his mistake, however, the unwrap() me开发者_如何学Gothod causes the field to lose focus.

$(special_input).live('keyup', function() {
    if (input_okay && input_had_errors) {
        $(this).unwrap();
    }
});

No big deal, I can reset the focus and it works fine...

$(this).unwrap().focus();

...everywhere but in IE! I've tried inserting a setTimeOut() function within the above function to get around IE's lack of support for bubbling of the focus() event, and that works... kinda.

Only problem is it sets the cursor to the beginning of whatever is being typed rather than the end. (WHAT?!)

Resetting the focus seems a little ugly anyway. Is there any way to keep unwrap() from unsetting it in the first place?

Thanks.

Kinda-solution:

For the reasons ender and elusive pointed out, I just decided to fix the problem of the misplaced cursor, which can be done by resetting the value of the textfield after focusing in on it once again. The code looks like this now.

$(this).unwrap();
setTimeout(function() { $(this).focus().val($(this).val()); }, 5);


I do not think that you can .unwrap() without loosing focus, since it removes the parent node from the DOM, and appends the children where the parent was afterwards. You could type in unattached input-fields if the browser wasn't removing focus when detaching them.


I agree with elusive that it is unlikely that you can .unwrap() without losing focus, for the reasons cited. You might consider the reason you are wrapping the text field in the first place. Is it possible you might achieve the same affect by simply applying a class to the field, or with a div placed before or after the field? This would allow you to circumvent the issue altogether.

0

精彩评论

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

关注公众号