javascriptjqueryhtmlbootstrap-tokenfieldmousetrap

Focus on bootstrap-tokenfield input


I would like to have focus on the tokenfield input field when the modal shows up. Currently it's focused only if I click on the input field in the modal.

https://jsfiddle.net/csisanyi/h19Lzkyr/12/

I tried to add the following code

    Mousetrap.bind('w', function() { 
  document.getElementById("keywordButton").click();
  document.getElementById("keyword-input").focus();
  }); 

I also tried to add <input autofocus> but when the tokenfield is initialized it seems like it's overriden.

I have checked the bootstrap-tokenfield documentation but input field focus is not really mentioned there.

Any suggestions?


Solution

  • I found a solution to the problem.

    after the tokenfield is initialized, bootstrap-tokenfield.js appends the id of the input with -tokenfield.

    So i added the following code.

    https://jsfiddle.net/csisanyi/h19Lzkyr/43/

    Mousetrap.bind('w', function() { 
      document.getElementById("keywordButton").click();
      setTimeout(() => {
              document.getElementById("keyword-input-tokenfield").focus();
            }, 400);
    }); 
    

    And it works with setting a minimal timeout on the focus expression.