2

So I've looked around at doing this as I need to get around an iOS bug, and none of my simulated clicks seem to work. I'm trying to manually focus on a textarea element but to do that I need to manually simulate a click on said textarea element. So here's what I've tried:

$('#text-input')[0].click();
$('#text-input').click();
$('#text-input').trigger('click');
$('#text-input').focus();

and

$('#text-input').on('click', function {
    $(this).focus();
});

$('#text-input').trigger('click');

$('#text-input').on('touchstart', function {
    $(this).focus();
});

$('#text-input').trigger('touchstart');

HTML:

<textarea id="comment-input" class="comment-input" rows="1" maxlength="{{maxTextLength}}" ng-model="newMessage.content" placeholder="{{ messagePlaceholder }}" />

Any thoughts on why this isn't working?

germainelol
  • 3,231
  • 15
  • 46
  • 82
  • can we see the HTML? – Mark C. Jun 10 '15 at 03:22
  • Seems to be a bug. Ref [1](http://stackoverflow.com/questions/979309/how-do-i-focus-an-html-text-field-on-an-iphone-causing-the-keyboard-to-come-up) and [2](https://github.com/jquery/jquery-mobile/issues/3016) – Drakes Jun 10 '15 at 03:45
  • @Drakes I know it's a bug, I'm trying to do a workaround for it. – germainelol Jun 10 '15 at 04:17
  • Some folks had progress with click for inputs, and could be extended to textarea. Ref [here](http://stackoverflow.com/questions/18728166/programatically-focus-on-next-input-field-in-mobile-safari) and [here](http://stackoverflow.com/questions/12204571/mobile-safari-javascript-focus-method-on-inputfield-only-works-with-click) – Drakes Jun 10 '15 at 04:20
  • @Drakes I've already looked at these too and I'm still unsure of a solution – germainelol Jun 10 '15 at 04:30

1 Answers1

0

try .focus instead of click like

$('#text-input').trigger('focus');

or Just

$('#text-input').focus();

UPDATE

You can try setTimeout which works in most case

$("#text-input").on("click", function(event) {
  setTimeout(function() {
        $(event.target).select(); //or $(event.target).focus();
  }, 1); 
});

UPDATE 2

You can also try to use touchstart event like

//trigger touch on element to set focus
$("#text-input").trigger('touchstart'); 

//event handler to set the focus()
$('#text-input').on('touchstart', function () {
    $(this).focus();   // inside this function the focus works
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200