12

I have a UIWebView and I want to set one of it's text field to certain text. Is that even possible? If so, how can I do that? Thanks

Dexter
  • 125
  • 1
  • 6

2 Answers2

24

Yes you can set the text for a textfield in the UIWebView using javascript

As an example if you have a textfield in this form

<input id="textFieldID" type="text" value="TextValue"/>

Setting value:

[theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('textFieldID').value = 'Hello World'"]

Getting value:

NSString* value = [theWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('textFieldID').value"];
Cyprian
  • 9,423
  • 4
  • 39
  • 73
  • How can i find out the id of the textfield, thanks for the reply. – Dexter May 22 '11 at 18:25
  • Depending on what type of field you want to access, you can always get the fields with: document.getElementsByTagName() where you then specify whether you need TEXTAREA, INPUT or SELECT and then just select the one from the array it returns. If you want to get the second input field from the whole page, you just : document.getElementsByTagName('INPUT')[1].value – margusholland May 22 '11 at 22:20
  • in document.getElementsByTagName('INPUT')[1].value, what code would be there if i want all the list of TextFields inside a WebView – nidIOS Mar 26 '14 at 07:19
2

In Swift-5 with WKWebView use this

To set text field

webView.evaluateJavaScript("document.getElementById('textFieldID').value = 'Hello'") { (result, error) in
   print(result) //This will Print Hello
}

To get the value of text field

webView.evaluateJavaScript("document.getElementById('textFieldID').value") { (result, error) in
   print(result) //This will Print value of text field
}
Avneesh Agrawal
  • 916
  • 6
  • 11