开发者

how to track when user presses enter on a drop down list option with jQuery?

I have a HTML form with a drop down list. I want to get the selected drop down value when the user select an option by arrow keys and presses enter key on one of the drop down options

HTML code:

<select>
  <option value="volvo">Volvo</option开发者_C百科>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

When the user selects Mercedes and presses enter I want to get that value. I can get that value by

$('option').live('click',function(){

var text = $(this)

});

but I want to get it when they press the enter key


Here is a working example.

$('select').live('keypress',function(e){
    var key = e.which;
    if(key == 13)// the enter key code
        {
            // do your thing
        }
});

As oezi said, you might be looking for the change event, but if you really want to capture the enter keypress, this is the way to do it.


Here is your solution please try

<!DOCTYPE html>
<html>
<head>

  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>


<select id="ddlDemo">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<script>



$('#ddlDemo').keyup(function(event) {
if(event.which==13)
{
  var text = $(this).val();
  alert(text);
}

});

</script>



</body>
</html>


The change event is probably the right way to go here. However, if you ever need something to work only on pressing enter, here is an example:

$('select').live('keydown', function(e){
    if (e.keyCode == 13) {
        var text = $(this)
    }
});

13 is the keycode for the enter key.

http://jsfiddle.net/z9q8Z/2/


what you're looking for is the change-event:

$('select').change(function(){

  var text = $(this).val();
  // whatever to do here

});

or, using .live() (if this is neccessary for you):

$('select').live('change',function(){

  var text = $(this).val();
  // whatever to do here

});

for more information, take a look at the documentation.

PS: you shouldn't bind events to the options, the select is the form-element and should be used to bind events on.

EDIT: added an example for live(), thanks to pyvi for the hint.


I tried the following JQuery script and it works with me.

$("#ddlName").keypress(function (e) {
    var key = e.which;

    if (key === 13)// the enter key code
    {
        // Handle enter key
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜