使用Jquery选择自动焦点下拉列表

时间:2016-05-24 06:25:07

标签: javascript jquery

我正在尝试单击一个按钮,该按钮将使用焦点和输入按钮触发选择按钮的下拉列表。但是输入不会触发。这是我的代码

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
  </head>

  <body ng-controller="myCtrl">
    <button id="showButton">Click Me!</button>
    <select id="show">
      <option value=""></option>
      <option value="">One</option>
      <option value="">Two</option>
      <option value="">Three</option>
    </select>
    <input type = "text" id="dean">
    <script type="text/javascript">
      $("#showButton").click(function(){
        $("#show").focus();
        e = $.Event('keyup');
        e.keyCode= 13; // enter
        $('#show').trigger(e);
      });
    </script>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

这可能仅适用于Chrome。

$aConfig['upload_path'] = 'path';//path where to upload file

$aConfig['allowed_types'] = 'mime type';// the file format which has to accepted

$aConfig['file_name'] = strtolower(date('Y').$_FILES['file']['name']);

$this->upload->initialize($aConfig);
$this->upload->do_upload('pdf');
$("#showButton").click(function() {
  var e = new MouseEvent('mousedown',  {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
  
  $("#show")[0].dispatchEvent(e);
});

答案 1 :(得分:1)

我会查看类似的内容:

Trigger a select form element to show its options (open drop down options list) with Javascript

<强> HTML

<input type="button" id="show" value="show" />
<select id="myslect">
    <option>nothing</option>
    <option>something</option>
    <option>anything</option>
</select>

<强> JAVASCRIPT

$("#show").click(function () {
    var element = $("select")[0],
        worked = false;
    if(document.createEvent) { // all browsers
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            worked = element.dispatchEvent(e);
    } else if (element.fireEvent) { // ie
        worked = element.fireEvent("onmousedown");
    }
    if (!worked) { // unknown browser / error
        alert("It didn't worked in your browser.");
    }
});

另一种解决方案是模仿下拉列表并切换该下拉列表的状态。这不是最好的方法,但是你可以完全控制元素。