15

I am loading an HTML page that has a form. I would like to be able to dismiss the keyboard when the user clicks on GO or if he clicks on the SUBMIT button on the HTML page.

If the user decides he doesn't want to fill out the form, I also need a way to dismiss the keyboard.

Not sure how to do this.

Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556

5 Answers5

34

A more concise way without needing to know what element is selected is the following:

[webView stringByEvaluatingJavaScriptFromString:@"document.activeElement.blur()"];
Sam Soffes
  • 14,831
  • 9
  • 76
  • 80
30

The javascript approach is clever, but this is more direct:

[webView endEditing:YES];
Christopher Pickslay
  • 17,523
  • 6
  • 79
  • 92
  • 3
    Note that this won't work if you're presenting a modal view on iPad with presentation style `UIModalPresentationFormSheet`. It is intended iOS behaviour - see: https://devforums.apple.com/message/166801#166801 . – matm Jul 26 '12 at 20:27
13

You can use javascript to take the focus away from the HTML text field using blur:

document.foo.bar.myinput.blur();
dstnbrkr
  • 4,305
  • 22
  • 23
  • also, check this out: http://stackoverflow.com/questions/866419/iphone-keyboard-in-uiwebview-does-not-go-away – dstnbrkr Apr 02 '10 at 20:07
2

UIGestureRecogniser will help to dismiss the keyboard when user clicks on the WebView. Here is the piece of code i used.

let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        tap.delegate = self 
        webView.addGestureRecognizer(tap)

@objc func handleTap(_ sender: UITapGestureRecognizer) { webView?.endEditing(true) }

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
  return true
}

Hope the helps.

-11

I'm not so familiar with UIWebView, but normally you would dismiss your keyboard like so...

[textField resignFirstResponder];

By doing that, the keyboard would be dismissed...

To have the keyboard be dismissed when say the user clicks the return button, you would need to implement the delegate method.

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{   
    [textField resignFirstResponder];
    return YES;
}

Apple's documentation has a full list of methods for the UITextFieldDelegate.

Rama Rao
  • 1,043
  • 5
  • 22
avizzini
  • 789
  • 1
  • 7
  • 17