bootstrap-select with custom buttons&动态添加新值

The*_*ris 23 ajax jquery dropdownbox dom-events twitter-bootstrap-3

在此输入图像描述我需要使用可以执行该功能的下拉列表:

  1. 动态地从数据库中提取和加载值
  2. 有一个嵌入式搜索框
  3. 每个Li上有2个自定义按钮,一个用于删除,一个用于编辑.
  4. 搜索字段,如果搜索到的文本不存在,则在"输入"按下,在同一选择上添加,也可以在Ajax数据库上添加.

我从silviomoreto git存储库中选择了@twitter bootstrap'bootstrap-select'的自定义选择,因为我没有找到我想要的功能,我试图自己制作它.

因此,对于那些需要或想要在他们的网络应用程序上添加该功能的人,我写下我的解决方案,这不是最好的解决方案,但它有效,我愿意接受任何建议,使其更好地工作.

1.步骤:创建一个带参数的selectpicker: data-size ="5"(显示5个值和添加滚动条),data-live-search ="true"(在顶部添加搜索框) 并加载值我从db(最好是ajax)获得:

       <select class="selectpicker typedropdown" data-size="5" data-live-search="true">
                            <?php
                            $counter=0;
                            foreach($eventTypeList as $evType){
                                $counter++;
                                if(is_array($evType)){
                                    echo "<option>".$evType['type_name']."</option>";
                                }else{
                                    echo "<option>".$evType."</option>";
                                }

                            } ?>
                        </select>
Run Code Online (Sandbox Code Playgroud)

2.步骤:添加自定义按钮(编辑,删除) (覆盖原型函数'createLi')

覆盖主js文件上的原型函数'createLi',如下所示:

  $.fn.selectpicker.Constructor.prototype.createLi = function (){..}
Run Code Online (Sandbox Code Playgroud)

内部:

var generateLI = function (content, index, classes, optgroup) {
        return '<li' + ........
Run Code Online (Sandbox Code Playgroud)

在'return'之前添加两行按钮类:

content += "<div class='removeTypebtn'></div><div class='editTypebtn'></div>";
Run Code Online (Sandbox Code Playgroud)

这样,当您创建li项目时,您还会在每行上创建两个自定义按钮.

3. step:捕获'click'事件进行编辑和删除值 (也在数据库上发出ajax请求以更新dbtable)

$(document.body).on('click','.btn-group.typedropdown .dropdown-menu ul li .removeTypebtn',function(event){
        var index = $(event.target).closest( "li" ).data('original-index');//get the item index
        var type_name = $(event.target).closest( "li" ).text();
        deleteType(index,type_name);
    });
Run Code Online (Sandbox Code Playgroud)

以类似的方式我们捕获'编辑项'的'click'事件,所以我省略了它.

现在我们需要做一个有趣的部分,从selectpicker中删除所选项目,并发出一个ajax请求从dbtable中删除它. 数据库超出了教程范围,所以,我把它留下来. 注意成功功能内部如何删除.

function deleteType(index,type_name){
        var url = "<?php echo $domain.$deleteType; ?>";
        data = {'index':index,'type_name':type_name};
        $.ajax({
            cache: false,
            url : url,
            type: "POST",
            data : data,
            success : function(data, textStatus, jqXHR){
                $('.typedropdown').find('[data-original-index=$index]').remove();//remove selected item from selectpicker
            $('.typedropdown').find('option:contains($type_name)').remove();";// remove value also from the hidden select
                $('.selectpicker.typedropdown').selectpicker('val', []);//clear selected
            },
            error : function(xhr, ajaxOptions, thrownError){
                alert(thrownError);
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)

4.步骤:在Enter上创建"添加新值"功能 (如您所知,搜索字段仅允许在li内搜索)

因此,当我们初始化selectpicker组件时,我们通过更改参数来更改' noneResultsText '消息:noneResultsText:

//init selectpicker
    selectPickerType = $('.selectpicker.typedropdown').selectpicker({
        noneResultsText:'Add new {0}',
        selectOnTab: true
    });
Run Code Online (Sandbox Code Playgroud)

所以,现在每当我们写下一个不存在的新单词时,我们会收到消息Add new'myword'

现在我们需要捕获click 事件.

$('.selectpicker.typedropdown').data('selectpicker').$searchbox.on('keydown',function(e){
            if(e.keyCode == 13){
                addNewDropdownValue(e.target.value,'type');
                return false;
            }
        });
Run Code Online (Sandbox Code Playgroud)

addNewDropdownValue函数:( dbj 的ajax请求添加新值)(注意成功函数)

function addNewDropdownValue(newValue,tble){
    var url = "<?php echo $domain.$addDropdownValueURL; ?>";
    data = {'newValue':newValue,'tble':tble};
    var loading = $('.loading');
    $.ajax({
        cache: false,
        url : url,
        type: "POST",
        data : data,
        beforeSend: function( xhr ) {
            loading.css('top',screen.height/2);
            loading.css('left',screen.width/2);
            loading.html('<div><img alt="loading..." src="<?php echo $domain; ?>/assets/images/loader/ajax_loader_blue_48.gif" /></div>').show();
        },
        success : function(data, textStatus, jqXHR){
            loading.fadeOut(500);
            $('.selectpicker.".$tble."dropdown').append('<option selected>$newValue</option>');//append new item on the selectpicker
            $('.selectpicker.".$tble."dropdown').val('$newValue');//select the new value
            $('.selectpicker.".$tble."dropdown').selectpicker('refresh');//refresh the selectpicker
            $('.".$tble."dropdown').removeClass('open');//close the selectpicker
        },
        error : function(xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

就是这样,现在我们有一个自定义引导选择器,每行都有删除和编辑按钮,并在输入时添加新的文本功能.

请以任何方式,请告诉我您如何使其更好地工作或如果您有任何问题.

Tim*_*ody 0

如何做得更好就是将 PHP 从等式中删除。事实上,删除生成 html 或 DOM 元素的任何服务器端代码。这将为您留下两部分:用于呈现 UI 的 javascript 和通过 API(node.js 等)的数据库方法。

实现将类似于以下内容 -

$.ajax({
  url: "/api/databaseCall/",
  success: function(data){

/* 
Build DropDown
the data variable will be a hash or array of returned db results
iterate over them and build UI
*/

    for(var i=0; i < data.results.length; i++){

      var row = '<option id=' + data.results[i].id + '>' + data.results[i].value + '</option>';
      $(".dropdown").append(row);
    } 

  }
});
Run Code Online (Sandbox Code Playgroud)

Angular、React、backbone 都是基于这种方法构建的。目前我唯一认可的是backbone.js。Backbone 非常容易学习。

一旦您使用 JavaScript 以编程方式构建 UI,任何功能都将使用像主干这样的框架自动绑定。