How to focus ons-input / textarea from JS Code?



  • Hi,

    i try to focus the text input from code (iOS App => KeyboardDisplayRequiresUserAction is already false)

    Whats the right API way? Or the workaround?

    I can focus the input, but the UI does not update.

    Kind regards.



  • Hey, I’m guessing you tried calling .focus(). What do you mean by “the UI does not update” - are you expecting some change from Onsen or only that the keyboard didn’t show?

    I tried these things, so I don’t know about the iOS settings. this cordova plugin seems to be doing some things with the keyboard but it looks like the show method is not available for iOS.

    A further search showed me this page, but this is completely random, so maybe try it and lets hope it works.

    Maybe some of the other members of he community have a better idea about these things.



  • @iqmeta I also am not exactly certain what you mean, but like @IliaSky I think you want to programatically set focus to a text input or text area and have it show the keyboard. Unfortunately, for iOS and Android, you can’t do this as far as I know. My understanding is that it is by default design from both OS’s as they only want the keyboard to show when a user wants it to show (not the developer! lol!). Anyway, the only ways to get around this, that I know of are:

    • window.prompt() opens the keyboard but it also forces a dialogue popup as well
    • If you trigger the .focus() from within a .click() event (e.g. from opening your dialog), the keyboard shows up

    So usually, I try to capture some user click event and then use that. Hope this helps.



  • hi, thanks for you answers… seems to be a iOS Mobile Safari WebView Problem. (iOS 9.3.4)
    I managed to open up the Keyboard on focus, but the Input only shows UI Updates / Typed letters when
    focused/clicked by touch.

    Tried a lot of thing like trigger touchstart etc.

    Onsen works on

    document.getElementById("onsInput")._input.focus()
    

    See:
    https://codepen.io/anon/pen/oLRLyb

    Intension was to focus ons-input on pressing a label/button somewhere else.

    Many thanks for your ideas.



  • Okay I got it… funny iOS…
    The Problem on top was in my case, I have this in an iframe…

    Don’t know why but focus the window (iframe) on each keydown makes everything works as it should.
    Dirty but works.

    This is why the touch worked before, it focuses the iframe too.

    So onclick on a button with this funktion shows the keyboard and typing works.

    function calledByClick(){
            var element = document.getElementById("onsInput")._input;
            var el = $(element);
            el.on('keydown', function() {
                window.focus()
                el.focus()
            });
            el.focus();
    }
    

    cheers.



  • @iqmeta Great! Good job! (^_^)


Log in to reply