Search code examples
jqueryhtmljquery-widgets

Unable to focus on jquery select widget dynamic input field


Basically I'm extending this question jQuery Combobox/select autocomplete? Here, I have updated the fiddle code here. The problem is that, if I met certain condition from the first menu(if the mainmenu selection value is two), I want to set focus in the input field in the the submenu. Here is my code: HTML:

<select id="mainmenu" style="width:300px">
    <option value>Select from menu</option>
    <option value="one">One</option>
    <option value="two">Two</option>
    <option value="three">Three</option>
</select>
<select id="submenu" style="width:300px">
    <option value>Select from submenu</option>
    <option value="a">A</option>
    <option value="b">B</option>
    <option value="c">C</option>
</select>

Script:

$(function(){
    $('select').combobox();
});

$( document ).ready(function() {

    console.log("console logging.");
    $('#mainmenu').change(function() {
            var selectVal = $('#mainmenu :selected').val();
            console.log("selected: " + selectVal);
            if(selectVal == 'two'){
                console.log("value: "+selectVal);
                //$('#submenu ~ input:first').autocomplete("search", "");
                $('#submenu ~ input:first').focus();
            }
        });
});

Solution

  • You need to bind onchange event of combobox like this $("#mainmenu").combobox({... and then set focus using $('#submenu').next().find('input').focus();

    Here's complete code:

    $( document ).ready(function() {
    $("#mainmenu").combobox({
            selected: function (event, ui) {
               var selectVal = $('#mainmenu :selected').val();
                if(selectVal=='two'){
                 $('#submenu').next().find('input').focus();
                }
            }
        });
    });
    

    DEMO