i have a dropdown menu - how can I trigger js function on keydown
So I hav开发者_如何转开发e a dropdown menu from an existing input field that is generated on the go. Lets say a search of friends. How can I triger a js function when user selects a friend with enter key. I can do it with the onclick js attribute but it seems not to work with onkeydown.
<% auto_complete_result_and_insert.each do |friend| %>
<li onkeydown="if (window.event.keyCode == 13) {alert('sth')}">
</li>
<% end %>
So the question is how can I detect when a user presses enter on my listed item?
I am not sure LI's (or any other non-focusable items for that point) can actually handle onkeydown events, since they can't have the focus. Keys work on items with focus.
Update: yeah, they can have focus as long as they have tabindex. Just assign different tabindex="1", 2 etc to the LI items.
Here's an example of how do to it with normal form fields
<script>
function handleKey(e){
var n = (window.Event) ? e.which : e.keyCode;
if (n == 13) {alert('sth')}
}
</script>
<select onkeydown="handleKey(event);">
<option value="test">test</option>
<option value="test">test</option>
</select>
If you're using Ruby on Rails, then you have the Prototype framework. Prototype will allow you to observe key down events.
Here's the link to the API: http://api.prototypejs.org/dom/event/
Here's the code you're looking for:
Event.observe(id_of_element, function(event) {
if(event.keyCode==13) {
// do your thang
}
});
精彩评论