Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preselect contenteditable field in UIWebView iOS5

First of all I know contenteditable is only iOS 5 I have accounted for this - we are giving users with iOS 5 a feature to allow Rich Text pasting using contenteditable. This feature works great so far all I want to do is when the view appears to set the contenteditable field as active (pre-select it) so that the keyboard appears and the user can begin typing right-away. Here is the local html file I am using for the UIWebView

<html>
    <body>
        <div id="content" contenteditable="true" style="font-family: Helvetica">PLACEHOLDER</div>
    </body>
</html>

I have already tried using some javascript to accomplish this using tutorials that I found for preselecting a text input. I could not get this to work, even when I tried to switch to a text input field for testing. This is probably due to my inexperience with javascipt so if that is the solution please be explicit (as I am completely unfamiliar with javascript).

Thanks for any help

like image 786
xizor Avatar asked Nov 03 '11 19:11

xizor


2 Answers

Now if anyone wants to achieve this in iOS 6, he can open iOS keyboard programmatically like this,

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    // keyboardDisplayRequiresUserAction available in iOS >= 6 
    if ([webView respondsToSelector:@selector(setKeyboardDisplayRequiresUserAction:)]) {
        webView.keyboardDisplayRequiresUserAction = NO;
    }
}

and then,

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    // Assuming that you're using jquery. If not, use document.getElementById('YourInputElementID')
    NSString *evalStr = [NSString stringWithFormat:@"setTimeout( function(){$('#YourInputElementID').focus();},1000);"];
    [webView stringByEvaluatingJavaScriptFromString:evalStr];
}

This will run this javascript after 1sec. For safe side you should call the get focus code when the focusing element has been loaded.

like image 71
Humayun Avatar answered Nov 20 '22 04:11

Humayun


Unfortunately you can't do that in Mobile Safari. I believe Apple chose to restrict this from happening because when you visit some sites, like Google for example, the search field gets focused immediately. This would be extremely annoying for users if every site they went to, the keyboard popped up. On Desktop this behaviour doesn't matter but on mobile devices it's very noticeable.

Related: Mobile Safari Autofocus text field

like image 4
sciritai Avatar answered Nov 20 '22 03:11

sciritai