简体   繁体   中英

how to set focus to autocomplete combobox?

At first accept my apology for bad English. I have 2 questions.

  1. I have two HTML elements on a page: input text, select option (autocomplete combo box). I want to focus on select option when I press enter on input text. How can I set focus to combo box?

  2. I have 2 elements like these.

     <input type="text" id="chosegender" /> <select id="gender"> <option value=""></option> <option value="m">male</option> <option value="f">female</option> </select> 

I want to select male when I press f on input tag and select m when I press m on input tag.

I'd appreciate you if you can help me to solve the problem.

To answer the first question, to transfer on the enter key you can use the following jquery code:

$('#chosegender').on('keypress', function(e) { 
    if(e.which == 13) {
        $('#gender').focus();
    } 
    return true;
});

I wasn't too sure what the actual goal was on the second part but I put together a snippet that should help:

$('#gender').on('keypress', function(e) {
    switch(e.which) {
        case 109: // m
        case 77:  // M
            $('#gender').val('f');
            break;
        case 102: // f
        case 70:  // F
            $('#gender').val('m');
            break;
    }
    return false;
});

I attached an event listener on the keypress event, you can use it on the keydown or keyup to access it earlier. On the second I returned false to in part cancel the bubble, but on some cases you might need to use the preventDefault() event method to prevent the browser from capturing the key. I've used this to prevent the default behavior of the tab key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM