温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

基于jquery实现多选下拉列表

发布时间:2020-09-23 19:11:11 来源:脚本之家 阅读:114 作者:wodeboke0219 栏目:web开发

本文实例为大家分享了jquery实现多选下拉列表展示的具体代码,供大家参考,具体内容如下

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
   ul li{
    list-style: none;
    }
   .hide{display: none}
   .width250{
    width: 150px;
    }
   .width250 input[type="text"]{
     width: 100%; 
     height: 32px; 
     border: 1px solid #ccc; 
     border-radius: 4px; 
     padding-left: 12px;
   }
    .width250 ul{ 
      width: 96%; 
      padding: 0 0 0 20px; 
      margin: 0; 
      border: 1px solid #ccc; 
    }
    .width250 li{ 
      padding: 5px; 
    }
    .width250 li+li{ 
      border-top: 1px solid #ccc; 
    }
  </style>
</head>
<body> 
  <form id="form">  
    <div class="width250">
      可多选年份:<input type="text" id="yearInput" placeholder="请选择年份" readonly>
      <ul id="yearId" class="hide">
      </ul>
    </div>
  </form>
</body>
<script type="text/javascript" src="jquery.js"></script>
<script>
  (function(){
    var str = '';
    var arr = {
      0 : {name:'2015',id:0},
      1 : {name:'2016',id:0},
      2 : {name:'2017',id:0}
    };
    for (let x in arr){
      console.info(x);
      str += `<li><label><input type="checkbox" value="${arr[x].id}" data-name="${arr[x].name}">${arr[x].name}</label></li>`;
    }
    $('#yearId').html(str);
  })();

  $("#yearInput").click(function(){
    $(this).attr('placeholder','');
    var name = '';
    $('#yearId input').each(function () {//循环遍历checkbox
      var check=$(this).is(':checked');//判断是否选中
      if(check){
        name += $(this).attr('data-name')+',';
        $(this).attr('name',"yearId");
      }else {
        $(this).attr('name',"");
      }
    });
    $("#yearInput").val(name.slice(0,-1));//去除最后的逗号
  });

  $("#yearId").mouseover(function() {
    if (!$("#yearId").hasClass('hover')){//类hover在下面用来验证是否需要隐藏下拉,没有其他用途。
      $("#yearId").addClass('hover');
    }
  }).mouseout(function(){
    $("#yearId").removeClass('hover');
  });

  $(document).on('click',function() {
    if (!$("#yearInput").is(":focus") && !$("#yearId").hasClass('hover')) {//如果没有选中输入框且下拉不在hover状态。
      var name = '';
      $('#yearId input').each(function () {//遍历checkbox
        var check = $(this).is(':checked');//判断是否选中
        if (check) {
          name += $(this).attr('data-name') + ',';
          $(this).attr('name', "yearId");
        } else {
          $(this).attr('name', "");
        }
      });
      $("#yearInput").val(name.slice(0, -1));//去除最后的逗号
      $("#yearId").addClass('hide');
    } else {
      $("#yearId").removeClass('hide');
    }
  });
</script>
</html>

效果图:

基于jquery实现多选下拉列表

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI