How can I focus on a selectize select box?
Asked Answered
W

5

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?

Wolsey answered 19/12, 2014 at 12:34 Comment(0)
L
25

You should use:

selectized[0].selectize.focus();
Lorenz answered 14/9, 2015 at 17:24 Comment(3)
This worked for me, .click() in the accepted answer did not.Brooch
@mike-c This is the option provided in the Selectize API. However it is a bit confusing how you access these methods. github.com/selectize/selectize.js/blob/master/docs/…Peppard
I've changed the answer to this as it's the proper way to do things according to the selectize authors, as you mention,Wolsey
C
7

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

$('.someclass input').click();
Crate answered 19/12, 2014 at 12:40 Comment(0)
T
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.

Tetreault answered 16/11, 2016 at 15:59 Comment(0)
R
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.

Rivi answered 23/5, 2017 at 15:30 Comment(0)
V
0

I found a easy way:

$("#selectid-selectized").focus(
  function () { 
    $("#selectid")[0].selectize.clear(); 
})
Virus answered 7/7, 2020 at 20:26 Comment(1)
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?Sense

© 2022 - 2024 — McMap. All rights reserved.