使用自定义按钮&自举选择随时添加新的价值 [英] bootstrap-select with custom buttons & add new values on the fly

查看:71
本文介绍了使用自定义按钮&自举选择随时添加新的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用可以执行此功能的下拉列表:

i needed to use a dropdown list that could do that functionality:

  1. 从数据库动态获取并加载值
  2. 具有嵌入的搜索框
  3. 每个Li上都有2个自定义按钮,一个用于删除,一个用于编辑.
  4. 搜索字段,如果搜索到的文本不存在,请在输入"按键上将其添加,或者在相同的选择< option> 上添加,也要在具有Ajax的数据库上添加.
  1. dynamically fetches and loads values from the database
  2. has an embeded search box
  3. has 2 custom buttons on each Li, one for delete and one for edit.
  4. the search field, if the searched text does not exist, add it on 'enter' press, either on the same select <option> and also on the database with Ajax.

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

I chose the custom select for @twitter bootstrap 'bootstrap-select' from silviomoreto git repository and because I did not find the functionality that I want i tried to make it on my own.

因此,对于那些需要或希望在其Web应用程序上添加该功能的人,我写下了我的解决方案,虽然它不是最好的解决方案,但它可以起作用,并且我乐于接受任何建议以使它更好地工作

So, for those that need or would like to add that functionality on their web-apps , I wrote down my solution, which is not the best solution but it works, and I am open to any suggestions to make it work better.

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

1. step: create a selectpicker with parameters : data-size="5" (show 5 values and the add scrollbar), data-live-search="true" (add the search box on the top) and load the values that I get from db (preferably with 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>

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

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

override the prototype function 'createLi' on your main js file like this:

  $.fn.selectpicker.Constructor.prototype.createLi = function (){..}

内部:

var generateLI = function (content, index, classes, optgroup) {
        return '<li' + ........

就在返回"之前,添加带有两个按钮类的行:

just before the 'return' add the line with tha two button classes :

content += "<div class='removeTypebtn'></div><div class='editTypebtn'></div>";

,因此,当您创建li项目时,还将在每行上创建两个自定义按钮.

3.步骤:捕获点击"事件以进行编辑和编辑删除值(还会在数据库上发出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);
    });

以类似的方式,我们为编辑项"捕获了点击"事件,因此我省略了它.

现在我们需要做的有趣的部分,从 selectpicker 中删除选定的项目,并发出ajax请求以将其从dbtable中删除.该数据库不在本教程的讨论范围之内,因此,我将其遗漏了.注意成功函数中的删除方法.

now we need to do the interesting part , to delete the selected item from the selectpicker and also make an ajax request to delete it from dbtable. the database is beyond the tutorial scope so , I left it out. pay attention inside the success function how I remove.

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);
            }
        });
    }

4.步骤:在Enter上创建添加新值"功能(您知道搜索字段仅允许在li的内部进行搜索)

所以,当我们初始化selectpicker组件时,我们通过更改 parameter:noneResultsText :

so, when we init the selectpicker component , we change the 'noneResultsText' message , by altering the parameter : noneResultsText :

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

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

现在,我们需要捕获点击 事件.

Now we need to catch the click event.

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

addNewDropdownValue 函数:(向dbtable发送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);
        }
    });
}

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

that's it , now we have a custom bootstrap select-picker with delete and edit buttons on each row and add new text functionality on enter.

请以任何方式告诉我您对我们如何使其更好地工作或您有任何疑问的看法.

please by any means, tell me your opinion on how we can make it work better or if you have any questions.

推荐答案

您可以通过忘记实际上启动了整个过程的PHP上端来使其工作更好.

You can make it work better by forgetting about that PHP up top that actually starts this whole thing.

假设您有一个javascript函数,该函数将ajax到服务器并获取值而不是该PHP代码.我们将其称为函数fetchData()

Suppose you had a javascript function that will ajax to the server and get the values instead of that PHP code. We will call it function fetchData()

fetchData()将从数据库中获取值,如果选择中包含任何值,则将其清空,然后将新值放入选择中.然后,您将继续附加事件.(编辑,删除等)

fetchData() will get the values from the database, empty the select if it has any values, and put the new values in the select. Then, you will continue to attach your events. (edit, delete, etc...)

现在在文档上准备好fetchData();

now on document ready fetchData();

在删除时,运行删除功能,然后运行fetchData();

on delete, run the delete function, then, fetchData();

在更新时,运行更新功能,然后运行fetchData();

on update, run the update function, then, fetchData();

在您可能想到的任何事件上,运行事件函数,然后运行fetchData();

on any event you can think of, run the event function, then fetchData();

此方法的优点在于,删除或更新时不必手动更新元素.另外,每次fetchData()时,您总是从数据库中获取新记录.

The beauty of this method is that you don't have to manually update your elements when you delete or update. Plus you are always getting new records from the database every time you fetchData().

想象一下,有10个不同的用户在10台不同的计算机上更新记录.以旧的用户身份,直到刷新页面,我才能看到其他用户的更新内容.但是现在我可以看到每次与页面进行交互,因为它将从数据库中获取并获取所有记录.

Imagine there are 10 different users updating records on 10 different computers. with the old way as a user, I wouldn't see what the other users updated until I refresh the page. but now I can see that every time I interact with the page because it will fetch from the database and get all the records.

您甚至可以更进一步,每30秒说一次fetchData();.因此即使我不与页面互动,我也总是会收到新信息的更新.

you can even take it a step further and say every 30 seconds fetchData(); so I'm always being updated with the new information even when I don't interact with the page.

这使您的代码干净.编写此函数后,您只需要担心少数事件,而不必担心在用户屏幕上发生事件后会发生什么,因为您始终调用fetchData(),并且完毕.而不是在他们删除选项时删除选项,或者在他们更新选项时更新选项的文本和值等.

This makes your code clean. You will only have to worry about a handful of events after you write this function, and you don't have to worry about what happens after the events, on the screen of the users, because you always call fetchData() and you're done. Instead of removing an option when they delete it or update text and value for an option when they update it etc..etc...

这篇关于使用自定义按钮&amp;自举选择随时添加新的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆