views:

651

answers:

3

I'm working on an application with an embedded UIWebView.

The user has the ability to enter a location in a text field in the web view but an effort is also made to discover the current location using Core Location.

If Core Location comes up with an accurate answer and the user is currently editing the location I'd like to cancel the editing and populate the location field programatically. This is based on the assumption that the vast majority of the time the user will want to use their current location and if they are editing the field they would rather that it was auto-populated than have to finish entering their location.

My question is this, how do I cancel editing within a UIWebView? If it was a normal text entry field I would force it to resign first responder and the keyboard would go away but I don't know how to do that with a UIWebView. Sending resignFirstResponder to the web view doesn't do it.

Is there something that can be done using Javascript and stringByEvaluatingJavaScriptFromString: on the web view? Is there another way?

A: 

Your best bet is the Javascript approach, look into form field focus values and see if you can make it drop focus.

It looks like what you may want is:

window.blur();

As per:

http://www.csie.ntu.edu.tw/~piaip/docs/GeckoDOM/dom_window_ref5.html

Kendall Helmstetter Gelner
Kendall, thank you very much for your answer, unfortunately it doesn't seem to work. I tried ' NSLog(@"javascript result %@",[mainWebView stringByEvaluatingJavaScriptFromString:@"window.blur();"]);' during editing and the keyboard stayed up and no errors were printed. Can you think of anything else to try?
oldbeamer
A: 

So the trick is to use 'blur()', but only on the field that is selected, not the whole window.

The following code snippet does the trick if 'self' is a subclass of UIWebView:

[self stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('textField')[0].blur();"];
oldbeamer
A: 

[webView stringByEvaluatingJavaScriptFromString:@"document.activeElement.blur();"];

William henderson