I want to fill in a text box inside a UIWebView, so I am using the following code to do so;
NSString *inputipjavascript = [NSString stringWithFormat:@"document.getElementById('IP').value = '%@';", enterip];
NSString *result;
[webView stringByEvaluatingJavaScriptFromString:inputipjavascript];
result = [webView stringByEvaluatingJavaScriptFromString:@"$('#GD').click();"];
The page which has the form on which I want to fill out automatically and submit is:
http://www.whatismyip.com/tools/ip-address-lookup.asp
The above code doesn’t work at all, what do I need to do?
The most likely explanation based on the limited details of the context of your code, is that you are ignoring the asynchronous nature of the
loadRequest:method and trying to execute your javascript commands before the DOM has loaded. Thus executing your commands on nothing. TheUIWebViewway to handle this is to use the-(void)webViewDidFinishLoad:(UIWebView *)webView;delegate method.Edit: To “I did this already, but it didn’t work.”.
After examining the page at your link:
http://www.whatismyip.com/tools/ip-address-lookup.asp. Your javascript is not compatible with the elements of your target webpage. For example here is the tag of the IP input field.<input type="text" name="IP" value="xxx.xxx.xxx.xxx">And you are trying to use
getElementById('IP')to get access to it. It has noidelement so you are not referencing anything. The most precise specifier is thenameelement, it’s value beingIP. The first method that came to mind wasgetElementsByName(), then I just have to use element[0].For a quick test I threw a few lines in an IBAction for a test and they worked for me: