13

Focusing on a select box (that has selectize enabled) does not focus on the selectized input box:

$('.someclass select').focus();

Focusing on selectize's own inout box doesn't seem to work either:

$('.someclass input').focus();

The Selectize docs mentions focus but that doesn't seem to work either. See this jsfiddle:

var selectized = $('#selectize').selectize();
selectized.focus();

I would expect the carat | to be ready and typing to immediately go into the box.

How can I focus on a selectize select box from JavaScript, so a user can type into it?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
mikemaccana
  • 110,530
  • 99
  • 389
  • 494

5 Answers5

25

You should use:

selectized[0].selectize.focus();
amdramdas
  • 513
  • 5
  • 5
  • 1
    This worked for me, .click() in the accepted answer did not. – connectedsoftware Jan 23 '16 at 20:18
  • 2
    @mike-c This is the option provided in the Selectize API. However it is a bit confusing how you access these methods. https://github.com/selectize/selectize.js/blob/master/docs/api.md#methods_other – eriksssss Mar 15 '17 at 20:16
  • 2
    I've changed the answer to this as it's the proper way to do things according to the selectize authors, as you mention, – mikemaccana May 23 '17 at 19:35
7

One way which appears to work is to call click() instead of focus():

$('.someclass input').click();
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
2

$('.someclass input') returns a jquery object (wrapped set - see What does jquery $ actually return?). You don't want the wrapped set, you want the first element in the set that matches the selector.

Try $('.someclass input')[0].selectize.focus(); instead.

Community
  • 1
  • 1
fatpanther
  • 115
  • 1
  • 6
0

For me $('.someclass input').focus() did the job. Firstly you choose your selectize element $('.someclass'), afterwards you choose to select only the input for that element $('.someclass input') and finally you trigger the focus() function on the element.

0

I found a easy way:

$("#selectid-selectized").focus(
  function () { 
    $("#selectid")[0].selectize.clear(); 
})
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • Matthew, can you explain your answer a little and prove it from forking the questions JS fiddle. For instance, why would that callback make it work? – bryjohns Jul 07 '20 at 21:11