Question: I've needed to do some things on Change event of jQuery Autocomplete. It's working as I expected (doing these things after changing and losing focus). 

However, if I click on submit button or press Enter (that submits too) the Autocomplete Change event is only firing after submit's done and I need it before submitting.

I've already tried some things like trigger change event on submitting event and other palliative things but nothing worked (using Select event is not an option).

Answer: 
From [the docs](https://developer.apple.com/library/mac//documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/index.html#//apple_ref/occ/instp/NSApplication/mainWindow):

> 
> The value in this property is `nil` when the app’s storyboard or nib file has not yet finished loading. It might also be `nil` when the app is inactive or hidden.
> 
> 
> 

So, this is a perfectly normal thing to have happen, depending on the circumstances.
For me the accepted answer did not work. The documentation for `activate(ignoringOtherApps:)` says:

```
...you shouldn’t assume the app will be active immediately after sending this message.

```

For this reason, `mainWindow` will most likely remain `nil`. So for me the following works:

```
extension NSApplication {
  /// Activates the app so main window / key window are no longer `nil`. Pauses a bit between activations and keeps trying.
  /// - Parameter completion: completion called with the key / main window
  @objc public static func withKeyOrMainWindow(mainOnly: Bool = false, completion: @escaping (_ window: NSWindow)->Void) {
    DispatchQueue.main.async {
      let window = mainOnly ? NSApplication.shared.mainWindow : NSApplication.shared.keyWindow ?? NSApplication.shared.mainWindow
      if let window = window {
        completion(window)
      }
      else {
        // Activate the app
        NSApp.activate(ignoringOtherApps: true)

        // Short delay
        DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
          NSApplication.withKeyOrMainWindow(completion: completion)
        }
      }
    }
  }

  /// Activates the app so main window is no longer `nil`. Pauses a bit between activations and keeps trying.
  /// - Parameter completion: completion called with the main window
  @objc public static func withMainWindow(completion: @escaping (_ window: NSWindow)->Void) {
    return withKeyOrMainWindow(mainOnly: true, completion: completion)
  }
}

```

Usage:

```
NSApplication.withKeyOrMainWindow { window in
  alert.beginSheetModal(for: window) { (response: NSApplication.ModalResponse) in
        handler?(response)
  }
}

```