Send focus to dynamic li with jQuery

醉酒当歌 提交于 2019-12-06 10:37:45

you need to just play with CSS & some jquery here. here is your fiddle. https://jsfiddle.net/7h0pavzb/ need to add a class to show that it is selected.

your jquery

$(document).ready(function(){
  $('#search_name').keyup(function(e) {
        if(e.which == 40){
            if($("#search_results li.active").length!=0) {
                var storeTarget = $('#search_results').find("li.active").next();
                $("#search_results li.active").removeClass("active");
                storeTarget.focus().addClass("active");
            }
            else {
                $('#search_results').find("li:first").focus().addClass("active");
            }
            return ;
        }
    });
});

and the style what i append is,

#search_results li.active { background:#000; color:#fff; }

here is another fiddle for up and down arrow key. https://jsfiddle.net/7h0pavzb/1/

Refering to jQuery's .focus() documentation

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

So simply add tabindex="10" attribute to your <li> tags so they can be focused. Or you can also wrap the LI's content into <a href="#"></a>, as links are focusable elements.

Another way to achieve this result would be by simply adding a class to your "focused" <li> tag.

user7418249

Just try below solution.

Hope it helps.

	$('#productname').keydown(function(e) {
  var key = e.which;
  if (key == 38 || key == 40) {
var storeTarget = "";

if (e.which == 40) {
  if ($("ul#suggestion-list li.active").length != 0) {
    storeTarget = $('#ul#suggestion-list').find("li.active").next();
    $("ul#suggestion-list li.active").removeClass("active");
    storeTarget.focus().addClass("active");
  } else {
    $('ul#suggestion-list').find("li:first").focus().addClass("active");
  }
  return;
}
  }
});
<div id="addproduct">
  <table>
<tr>
  <td>Product Name:</td>
  <td>
    <input type="text" name="" id="productname" placeholder="Product Name" size="40" />
  </td>
  <td> Quantity </td>
  <td>
    <input type="text" name="quantity" id="quantity" placeholder="QTY" size="3" />
  </td>
  <td>
    <input type="button" id="add" value="Add" />
  </td>
</tr>
<tr>
  <td></td>
  <td>
    <ul id="suggestion-list"></ul>
  </td>
  <td></td>
  <td></td>
  <td></td>
</tr>
  </table>
</div>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!