Button to force focus to hidden input?


#1

Here’s the problem I’m trying to solve. I want to have a button labeled, say “Set Height”, and when the user clicks it, I want it to pop up the telephone keyboard and let the user input a value that is bound to my model. I don’t want to use a visible input because I actually only want to display some crazy formatting of what they typed, not the number itself.

So my thought was to have a hidden form (either opacity or placing offscreen or whatever), like:

%input#height(type="tel" ng-model="height")

and then have my button do:

%button(ng-click="focusHeight()") Set Height

in focusHeight:

  @focusHeight = ->
    ionic.trigger('click', {target: $('#height')})
    return

I do have jquery loaded so the selector works. This doesn’t do anything, nor do other variations like $(’#height’).click() or $(’#height’).focus(). I’d really appreciate any insight on the best way to do this!


#2

on your input just ng-focus="setFocus" and on your button ng-click="setFocus=true"


#3

@Bonda thanks for the suggestion, but that doesn’t work either.


#4

(which would be expected that that doesn’t work, since ng-focus speficies a function to call when focus is received, it isn’t a boolean that grabs focus when true.)


#5

sorry, my bad, I usually get confused by ng-focus.
In this stackoverflow a guy has made a directive for focus a input when a button is clicked.

If you said that have jquery loaded, you can use this function to focus the element

angular.element('.selector').trigger('focus');

#6

Yeah, that works in a vanilla angular project but doesn’t seem to work with ionic. (That was the first thing I tried, I should have mentioned). I spent awhile debugging it and didn’t land on the answer yet, so for now I’ve gone for a workaround, but any help would be appreciated.


#7

In one ionic project i used native javascript like this line:

document.getElementById("myInput").focus();

To focus or blur an input without using jquery. It worked quite well, but it was not hidden.
Maybe that is the issue here.

try to set input height to 0 or use visibility: hidden.

Greets, bengtler


#8

Ah the answer is here: https://github.com/driftyco/ionic/issues/822#issuecomment-48605203 - turns out it is a cordova level problem that you can solve with a preference.


#9

ah okay thank you for sharing.

i have this setting by default in my configs.