使用选择选项内的复选框

时间:2018-01-05 17:55:04

标签: jquery html css

客户端给了我一个设计,其中包含一个Select Option菜单,其中包含一个checkBox以及项目名称作为列表中的单个项目。所以对于这个我谷歌它,并发现以下代码。



// MultiSelectBox, Kendo Plugin
// -----------------------------------------------------------
(function ($) {
    var MultiSelectBox = window.kendo.ui.DropDownList.extend({

        init: function (element, options) {
            var me = this;
            // setup template to include a checkbox
            options.template = kendo.template(
                kendo.format('<input type="checkbox" name="{0}" value="#= {1} #" />&nbsp;<label for="{0}">#= {2} #</label>',
                    element.id + "_option_" + options.dataValueField,
                    options.dataValueField,
                    options.dataTextField
                )
            );
            // create drop down UI
            window.kendo.ui.DropDownList.fn.init.call(me, element, options);
            // setup change trigger when popup closes
            me.popup.bind('close', function () {
                var values = me.ul.find(":checked")
                    .map(function () { return this.value; }).toArray();
                // check for array inequality
                if (values < me.selectedIndexes || values > me.selectedIndexes) {
                    me._setText();
                    me._setValues();
                    me.trigger('change', {});
                }
            });
        },

        options: {
            name: "MultiSelectBox"
        },

        selectedIndexes: [],

        _accessor: function (vals, idx) { // for view model changes
            var me = this;
            if (vals === undefined) {
                return me.selectedIndexes;
            }
        },

        value: function (vals) {
            var me = this;
            if (vals === undefined) { // for view model changes
                return me._accessor();
            } else { // for loading from view model
                var checkboxes = me.ul.find("input[type='checkbox']");
                if (vals.length > 0) {
                    // convert to array of strings
                    var valArray = $(vals.toJSON())
                        .map(function() { return this + ''; })
                        .toArray();
                    checkboxes.each(function () {
                        this.checked = $.inArray(this.value, valArray) !== -1;
                    });
                    me._setText();
                    me._setValues();
                }
            }
        },

        _select: function(li) { }, // kills highlighting behavior
        _blur: function () { }, // kills popup-close-on-click behavior

        _setText: function () { // set text based on selections
            var me = this;
            var text = me.ul.find(":checked")
                .map(function () { return $(this).siblings("label").text(); })
                .toArray();
            me.text(text.toString().replace(/,/g, ', '));
        },
        _setValues: function () { // set selectedIndexes based on selection
            var me = this;
            var values = me.ul.find(":checked")
                .map(function () { return this.value; })
                .toArray();
            me.selectedIndexes = values;
        }

    });

    window.kendo.ui.plugin(MultiSelectBox);

})(jQuery);
// ===========================================================

// view model
// -----------------------------------------------------------
var testVM = kendo.observable({
    testItems: [1,3],
    testItemSource: new kendo.data.DataSource({
        data: [
            { Id: 1, Name: "Test 1" },
            { Id: 2, Name: "Test 2" },
            { Id: 3, Name: "Test 3" },
            { Id: 4, Name: "Test 4" }
        ]
    }),
});
// ===========================================================

$(document).ready(function () {
    kendo.bind($("#testView"), testVM);
});
&#13;
<div id="testView">
    <input id="testItems" data-role="multiselectbox" data-text-field="Name" data-value-field="Id" data-bind="source: testItemSource, value: testItems" />
</div>
&#13;
&#13;
&#13;

我想要这样的东西。但不完全是这个。我想在html中使用select选项,因为我正在开发一个php站点。完整的代码链接: - http://jsfiddle.net/bDvkQ/

1 个答案:

答案 0 :(得分:0)

我认为你看起来像这样

// variable_names
// functionNames
// CONSTANT_VARIABLE_NAMES
// $_my_jquery_selected_element

if(typeof String.prototype.trim !== 'function') {
    
    String.prototype.trim = function()
    {
        return this.replace(/^\s+|\s+$/g, '');
    }
}

var checkbox_select = function(params)
{
    // Error handling first
    // ----------------------------------------------------------------------------------------------------
    
    var error = false;

    // If the selector is not given
    if(!params.selector) {                                              console.error("selector needs to be defined"); error = true; }

    // If the selector is not a string
    if(typeof params.selector != "string") {                            console.error("selector needs to be a string"); error = true; }

    // If the element is not a form
    if(!$(params.selector).is("form")) {                                console.error("Element needs to be a form"); error = true; }

    // If the element doesn't contain a select
    if($(params.selector).find("select").length < 1) {                  console.error("Element needs to have a select in it"); error = true; }

    // If the element doesn't contain option elements
    if($(params.selector).find("option").length < 1) {                  console.error("Select element needs to have an option in it"); error = true; }

    // If the select element doesn't have a name attribute
    if($(params.selector).find('select').attr('name') == undefined) {   console.error("Select element needs to have a name attribute"); error = true; }

    // If there was an error at all, dont continue in the code.
    if(error)
        return false;

    // ----------------------------------------------------------------------------------------------------

    var that            = this,
        $_native_form   = $(params.selector),
        $_native_select = $_native_form.find('select'),
        
        // Variables
        selector                = params.selector,
        select_name             = $_native_select.attr('name').charAt(0).toUpperCase() + $_native_select.attr('name').substr(1),
        selected_translation    = params.selected_translation   ? params.selected_translation   : "selected",
        all_translation         = params.all_translation        ? params.all_translation        : "All " + select_name + "s",
        not_found_text          = params.not_found              ? params.not_found              : "No " + select_name + "s found.",
        currently_selected      = [],
        
        // Create the elements needed for the checkbox select
        $_parent_div    = $("<div />")      .addClass("checkbox_select"),
        $_select_anchor = $("<a />")        .addClass("checkbox_select_anchor")     .text( select_name ),
        $_search        = $("<input />")    .addClass("checkbox_select_search"),
        $_submit        = $("<input />")    .addClass("checkbox_select_submit")     .val("Apply") .attr('type','submit') .data("selected", ""),
        $_dropdown_div  = $("<div />")      .addClass("checkbox_select_dropdown"),
        $_not_found     = $("<span />")     .addClass("not_found hide")             .text(not_found_text),
        $_ul            = $("<ul />"),

        updateCurrentlySelected = function()
        {
            var selected = [];

            $_ul.find("input:checked").each(
                                                        
                function()
                {
                    selected.push($(this).val());
                }
            );

            currently_selected = selected;

            if(selected.length == 0)
            {
                    $_select_anchor.text( select_name )
            }
            else if(selected.length == 1)
            {
                $_select_anchor.text( selected[0] + " " + selected_translation );
            }
            else if(selected.length ==  $_ul.find("input[type=checkbox]").length)
            {
                $_select_anchor.text( all_translation );
            }
            else
            {
                $_select_anchor.text( selected.length + " " + selected_translation );
            }
        },

        // Template for the li, will be used in a loop.
        createItem  = function(name, value, count)
        {
            var uID             = 'checkbox_select_' + select_name + "_" + name.replace(" ", "_"),
                $_li            = $("<li />"),
                $_checkbox      = $("<input />").attr(
                                        {
                                            'name'  : name,
                                            'id'    : uID,
                                            'type'  : "checkbox",
                                            'value' : value
                                        }
                                    )
                                    .click(

                                        function()
                                        {
                                            updateCurrentlySelected();
                                        }
                                    ),

                $_label         = $("<label />").attr('for', uID),
                $_name_span     = $("<span />").text(name).prependTo($_label),
                $_count_span    = $("<span />").text(count).appendTo($_label);
                        
            return $_li.append( $_checkbox.after( $_label ) );
        },
		
		apply = function()
		{
			$_dropdown_div.toggleClass("show");
			$_parent_div.toggleClass("expanded");
				
			if(!$_parent_div.hasClass("expanded"))
			{  
				// Only do the Apply event if its different
				if(currently_selected != $_submit.data("selected"))
				{
					$_submit.data("selected" , currently_selected);

					that.onApply(
						{ 
							selected : $_submit.data("selected")
						}
					);
				}		
			}					
		};
    
    // Event of this instance
    that.onApply = typeof params.onApply == "function" ? 
                
                    params.onApply :
                
                    function(e) 
                    {
                        //e.selected is accessible
                    };

    that.update = function() 
    {
        $_ul.empty();
        $_native_select.find("option").each(

            function(i)
            {
                $_ul.append( createItem( $(this).text(), $(this).val(), $(this).data("count") ) );
            }
        );

        updateCurrentlySelected();
    }

    that.check = function(checkbox_name, checked) 
    {
        //$_ul.find("input[type=checkbox][name=" + trim(checkbox_name) + "]").attr('checked', checked ? checked : false);

		$_ul.find("input[type=checkbox]").each(function()
		{
			// If this elements name is equal to the one sent in the function
			if($(this).attr('name') == checkbox_name)
			{
				// Apply the checked state to this checkbox
				$(this).attr('checked', checked ? checked : false);
				
				// Break out of each loop
				return false;
			}
		});
		
        updateCurrentlySelected();

    }

    // Build mark up before pushing into page
    $_dropdown_div  .prepend($_search);
    $_dropdown_div  .append($_ul);
    $_dropdown_div  .append($_not_found);
    $_dropdown_div  .append($_submit);
    $_dropdown_div  .appendTo($_parent_div);
    $_select_anchor .prependTo($_parent_div);

    // Iterate through option elements
    that.update();

    // Events 

    // Actual dropdown action
    $_select_anchor.click( 

        function()
        {
            apply();
        }
    );
             
    // Filters the checkboxes by search on keyup
    $_search.keyup(

        function()
        {
            var search = $(this).val().toLowerCase().trim();

            if( search.length == 1 )
            {
                $_ul.find("label").each(

                    function()
                    {
                        if($(this).text().toLowerCase().charAt(0) == search.charAt(0))
                        {
                            if($(this).parent().hasClass("hide"))
                                $(this).parent().removeClass("hide");

                            if(!$_not_found.hasClass("hide"))
                                $_not_found.addClass("hide");
                        }
                        else
                        {
                            if(!$(this).parent().hasClass("hide"))
                                $(this).parent().addClass("hide");

                            if($_not_found.hasClass("hide"))
                                $_not_found.removeClass("hide");
                        }
                    }
                );
            }
            else
            {
                // If it doesn't contain 
                if($_ul.text().toLowerCase().indexOf(search) == -1)
                {
                    if($_not_found.hasClass("hide"))
                        $_not_found.removeClass("hide");
                }
                else
                {
                    if(!$_not_found.hasClass("hide"))
                        $_not_found.addClass("hide");
                }
                    
                $_ul.find("label").each(

                    function()
                    {
                        if($(this).text().toLowerCase().indexOf(search) > -1)
                        {
                            if($(this).parent().hasClass("hide"))
                                $(this).parent().removeClass("hide");
                        }
                        else
                        {
                            if(!$(this).parent().hasClass("hide"))
                                $(this).parent().addClass("hide");
                        }
                    }
                );
            }
        }
    );

    $_submit.click(
                
        function(e)
        {
            e.preventDefault();

            apply();
        }
    );

    // Delete the original form submit
    $(params.selector).find('input[type=submit]').remove();

    // Put finalized markup into page.
    $_native_select.after($_parent_div);

    // Hide the original element
    $_native_select.hide();
};
body
{
  font-family: Open sans, Helvetica;
  background: #111;
  color: white;
  font-size: 16px;
}

h1
{
  font-weight: lighter;
}

small
{
  color: firebrick;
}

div.checkbox_select
{
  width: 200px;
}

.checkbox_select_anchor
{
  display: block;
  background: firebrick;
  color: white;
  cursor: pointer;
  padding: 10px 5px 5px;
  position: relative;
}

.checkbox_select_anchor:after
{
  width: 0; 
	height: 0; 
	border-left: 10px solid transparent;
	border-right: 10px solid transparent;
	border-top: 10px solid darkred;
  content: "";
  position: absolute;
  right: 10px;
  top: 15px;
}

.expanded .checkbox_select_anchor:after
{
	border-top: 0;
	border-bottom: 10px solid firebrick;
}


.checkbox_select_anchor:hover
{
  background: #FF3030 !important;
}

.expanded .checkbox_select_anchor
{
    background: #7C1818;
}

div.checkbox_select .select_input
{
    width: 100%;
    cursor: pointer;
}

.checkbox_select_dropdown
{
    display: none;
    background: whitesmoke;
}

.checkbox_select_dropdown.show
{
    display: block;
}

.checkbox_select_dropdown ul
{
    max-height: 150px;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 0;
  margin: 0;
      border: 1px solid #999;
  border-top: 0;
  border-bottom: 0;
}
.checkbox_select_dropdown ul li
{
    list-style: none;
    position: relative;
    color: #666;
}
.checkbox_select_dropdown ul li label
{
  position: relative;
      padding: 10px 5px 5px 40px;
     display: block;
  cursor: pointer;
}
.checkbox_select_dropdown ul li label:hover
{
  background: #cbcbcb;
  color: white;
}
.checkbox_select_dropdown ul li input:checked + label
{
  background: #bbb;
  color: white;
  text-shadow: 0px 1px 1px rgba(150, 150, 150, 1);
}
.checkbox_select_dropdown ul li input
{
  position: absolute;
  left:0;
  z-index:1;
  display: inline-block;
  height: 100%;
  width: 30px;
}
.checkbox_select_search
{
    width: 200px;
    padding: 10px 5px 5px;
    border: 1px solid #999;
      border-top: 0;
    -webkit-box-sizing: border-box;
	  -moz-box-sizing: border-box;
	  box-sizing: border-box;
}

.checkbox_select_submit
{
    background: #00A600;
    color: white;
    padding: 10px 5px 5px;
    border: 0;
    width: 100%;
    font-size: 14px;
    cursor: pointer;
}

.hide
{
    display: none;
}
<h1>Checkbox select</h1>

<form id="make_checkbox_select">

  <select name="make">
      <option data-count="2" value="Alfa Romeo">Alfa Romeo</option>
      <option data-count="23" value="Audi">Audi</option>
      <option data-count="433" value="BMW">BMW</option>
      <option data-count="45" value="Chrysler">Chrysler</option>
      <option data-count="476" value="Citroen">Citroen</option>
      <option data-count="78" value="Dodge">Dodge</option>
      <option data-count="123" value="Fiat">Fiat</option>
      <option data-count="32" value="Ford">Ford</option>
      <option data-count="3" value="Honda">Honda</option>
      <option data-count="342" value="Hyundai">Hyundai</option>
      <option data-count="45" value="Isuzu">Isuzu</option>
      <option data-count="653" value="Jaguar">Jaguar</option>
      <option data-count="3" value="Jeep">Jeep</option>
      <option data-count="23" value="Kia">Kia</option>
      <option data-count="5656" value="Lamborghini">Lamborghini</option>
      <option data-count="2133" value="Land Rover">Land Rover</option>
      <option data-count="2" value="Lexus">Lexus</option>
      <option data-count="43" value="Lotus">Lotus</option>
      <option data-count="54" value="Maserati">Maserati</option>
      <option data-count="5" value="Mazda">Mazda</option>
      <option data-count="1" value="Mercedes-Benz">Mercedes-Benz</option>
      <option data-count="34" value="Mini">Mini</option>
      <option data-count="23" value="Mitsubishi">Mitsubishi</option>
      <option data-count="56" value="Nissan">Nissan</option>
      <option data-count="98" value="Peugeot">Peugeot</option>
      <option data-count="210" value="Porsche">Porsche</option>
      <option data-count="3" value="Renault">Renault</option>
      <option data-count="76" value="Saab">Saab</option>
      <option data-count="45" value="Skoda">Skoda</option>
      <option data-count="3" value="smart">smart</option>
      <option data-count="23" value="Subaru">Subaru</option>
      <option data-count="7" value="Suzuki">Suzuki</option>
      <option data-count="45" value="Toyota">Toyota</option>
      <option data-count="23" value="Volkswagen">Volkswagen</option>
      <option data-count="6" value="Volvo">Volvo</option>
  </select>
  
  <input type="submit" />
  
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script>

	$(function()
	{
		var mySelectCheckbox = new checkbox_select(
		{
			selector : "#make_checkbox_select",
            selected_translation : "selectat",
            all_translation : "Toate marcile",
            not_found : "Nici unul gasit",

			// Event during initialization
			onApply : function(e)
			{
                alert("Custom Event: " + e.selected);
			}
		});
  
	});
		
</script>