选择值选择按键盘按钮

问题描述 投票:0回答:2

我正在制作一个系统,其中在模糊后添加html选项,用户需要从该选择框中选择一个选项。但是如果用户在键盘上按下相同的值键,我需要自动选择所选的值,就像按下2所选的值应为2。

$('input').on('blur', function() {
  $(this).after("<select class=\"form-control\"><option value=\"Option\">option</option><option value=\"2\">2 </option><option value=\"3\">3 </option><option value=\"4\">4</option><option value=\"5\">5 </option><option value=\"6\">6 </option><option value=\"7\">7 </option><option value=\"8\">8 </option></select>");
  $('.form-control').on('change', function() {
    $('input').after('<span>' + $(this).val() + '</span>');
    $(this).hide();
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
javascript jquery css html-select
2个回答
0
投票

只需将焦点设置到新的选择控件,就像将自动对焦属性赋予选择控件一样,应该可以解决问题。

$('input').on('blur',function(){
$(this).after("<select class=\"form-control\" tabindex=\"1\" autofocus><option value=\"Option\">option</option><option value=\"2\">2 </option><option value=\"3\">3 </option><option value=\"4\">4</option><option value=\"5\">5 </option><option value=\"6\">6 </option><option value=\"7\">7 </option><option value=\"8\">8 </option></select>");
$('.form-control').on('change',function(){
$('input').after('<span>'+$(this).val()+'</span>');
$(this).hide();
$('.text-control').val($('input').val() + $(this).val());
});
$('.form-control').focus();
})
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" class="text-control">

0
投票

如果用户仅模糊输入,则只显示选择框

然后,如果输入中有一些值,它将在选择框中被选中

我希望这有帮助

$('input').on('blur', function() {
  // check if the select is already present in the DOM
  if (!$(".form-control").length) {
    // get the input value
    var inputVal = $(this).val();
    
    // we start the select form before the loop
    var form = "<select class=\"form-control\"><option value=\"Option\">option</option>";

    // we loop from 2 to 8
    for (i = 2; i < 9; i++) {
      // if the selected value from the input match with the value of the loop var then we selected it
      var selected = (i == inputVal ? " selected" : "");
      form += "<option value=\"" + i +"\"" + selected + ">" + i +" </option>";
    };

    // we the the closing tag for the select
    form += "</select>";
    
    // we inject the form after the input
    $(this).after(form);
  }
  
  $('input').on('change', function() {
    // the value change in input so we get it
    var newVal = $.trim($(this).val());
    // we remove all selected attribut of all option in select
    $(".form-control option").removeAttr('selected');
    // then we add the selected attribut to the right option
    $('.form-control option[value="'+ newVal +'"]').prop("selected","selected");
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
© www.soinside.com 2019 - 2024. All rights reserved.