Extjs 多选下拉框 Ext.ux.form.LovCombo默认选择及其它BUG修复版支持多选/全选/全不选ext3.x

extjs 3.* 的多选下拉列表,支持单选,多选,全选全不选的功能,例子在文章最后。

文件名:lovcombo.js

if ('function' !== typeof RegExp.escape) {
	RegExp.escape = function(s) {
		if ('string' !== typeof s) {
			return s
		}
		return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1')
	}
}
Ext.ns('Ext.ux.form');
Ext.ux.form.LovCombo = Ext.extend(Ext.form.ComboBox, {
	checkField: 'checked',
	separator: ',',
	initComponent: function() {
		Ext.ux.form.LovCombo.superclass.initComponent.call(this);
		this.tpl = ['<tpl for=".">',
					'<div class="x-combo-list-item">',
					'<img src="' + Ext.BLANK_IMAGE_URL + '" class="ux-lovcombo-icon ux-lovcombo-icon-',
					'{[values.' + this.checkField + '?"checked":"unchecked"]}">',
					'<div class="ux-lovcombo-item-text">{' + (this.displayField || 'text') + '}</div>',
					'</div>',
					'</tpl>'
				].join("");

		this.on({
			scope: this,
			expand : function(){
				this.getValue()&&this.setValue(this.getValue());
			}
		});
		
		this.onLoad = this.onLoad.createSequence(function() {
			if (this.el) {
				var v = this.el.dom.value;
				this.el.dom.value = v
			}
		});
		this.store.on("load",function(){
			this.getValue()&&this.setValue(this.getValue());
		},this);
	},
	initEvents: function() {
		Ext.ux.form.LovCombo.superclass.initEvents.apply(this, arguments);
		this.keyNav.tab = false
	},
	clearValue: function() {
		this.value = '';
		this.setRawValue(this.value);
		this.store.clearFilter();
		this.store.each(function(r) {
			r.set(this.checkField, false)
		},this);
		if(this.hiddenField) {
			this.hiddenField.value = ''
		}
		this.applyEmptyText()
	},
	getCheckedDisplay: function() {
		var re = new RegExp(this.separator, "g");
		return this.getCheckedValue(this.displayField).replace(re, this.separator + ' ')
	},
	getCheckedValue: function(field) {
		field = field || this.valueField;
		var c = [];
		var snapshot = this.store.snapshot || this.store.data;
		snapshot.each(function(r) {
			if (r.get(this.checkField)) {
				c.push(r.get(field))
			}
		},this);
		return c.join(this.separator)
	},

	onBeforeQuery: function(qe) {
		qe.query = qe.query.replace(new RegExp(this.getCheckedDisplay() + '[ ' + this.separator + ']*'), '')
	},

	onSelect: function(record, index) {
		if (this.fireEvent('beforeselect', this, record, index) !== false){
			record.set(this.checkField, !record.get(this.checkField));
			if (this.store.isFiltered()) {
				this.doQuery(this.allQuery)
			}
			this.setValue(this.getCheckedValue());
			this.fireEvent('select', this, record, index)
		}
	},
	setValue: function(v) {
		if (v) {
			v = '' + v;
			if (this.valueField) {
				this.store.clearFilter();
				this.store.each(function(r) {
					var checked = !(!v.match('(^|' + this.separator + ')' + RegExp.escape(r.get(this.valueField)) + '(' + this.separator + '|$)'));
					r.set(this.checkField, checked)
				},this);
				this.value = this.getCheckedValue() || v;
				this.setRawValue(this.store.getCount()>0 ? this.getCheckedDisplay() : this.value);
				if (this.hiddenField) {
					this.hiddenField.value = this.value
				}
			} else {
				this.value = v;
				this.setRawValue(v);
				if (this.hiddenField) {
					this.hiddenField.value = v
				}
			}
			if (this.el) {
				this.el.removeClass(this.emptyClass)
			}
			if(this.selectall){
				if(this.getCheckedValue().split(",").length == this.store.getCount()){
					this.selectall.replaceClass("ux-combo-selectall-icon-unchecked","ux-combo-selectall-icon-checked");
				}else{
					this.selectall.replaceClass("ux-combo-selectall-icon-checked","ux-combo-selectall-icon-unchecked")
				}
			}
		} else {
			this.clearValue()
		}
		
	},
	initList : function(){
        if(!this.list){
            var cls = 'x-combo-list';

            this.list = new Ext.Layer({
                parentEl: this.getListParent(),
                shadow: this.shadow,
                cls: [cls, this.listClass].join(' '),
                constrain:false
            });

            var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
            this.list.setSize(lw, 0);
            this.list.swallowEvent('mousewheel');
            this.assetHeight = 0;
            if(this.syncFont !== false){
                this.list.setStyle('font-size', this.el.getStyle('font-size'));
            }
            if(this.title){
                this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
                this.assetHeight += this.header.getHeight();
            }
			
			if(this.showSelectAll){
				this.selectall = this.list.createChild({
					cls:cls + 'item ux-combo-selectall-icon-unchecked ux-combo-selectall-icon',
					html: "选择全部"
				});
				this.selectall.on("click",function(el){
					if(this.selectall.hasClass("ux-combo-selectall-icon-checked")){
						this.selectall.replaceClass("ux-combo-selectall-icon-checked","ux-combo-selectall-icon-unchecked");
						this.deselectAll();
					}else{
						this.selectall.replaceClass("ux-combo-selectall-icon-unchecked","ux-combo-selectall-icon-checked")
						this.selectAll();
					}
				},this);
				this.assetHeight += this.selectall.getHeight();
			}

            this.innerList = this.list.createChild({cls:cls+'-inner'});
            this.mon(this.innerList, 'mouseover', this.onViewOver, this);
            this.mon(this.innerList, 'mousemove', this.onViewMove, this);
            this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));

            if(this.pageSize){
                this.footer = this.list.createChild({cls:cls+'-ft'});
                this.pageTb = new Ext.PagingToolbar({
                    store: this.store,
                    pageSize: this.pageSize,
                    renderTo:this.footer
                });
                this.assetHeight += this.footer.getHeight();
            }

            if(!this.tpl){
                this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
            }

            this.view = new Ext.DataView({
                applyTo: this.innerList,
                tpl: this.tpl,
                singleSelect: true,
                selectedClass: this.selectedClass,
                itemSelector: this.itemSelector || '.' + cls + '-item',
                emptyText: this.listEmptyText
            });

            this.mon(this.view, 'click', this.onViewClick, this);

            this.bindStore(this.store, true);

            if(this.resizable){
                this.resizer = new Ext.Resizable(this.list,  {
                   pinned:true, handles:'se'
                });
                this.mon(this.resizer, 'resize', function(r, w, h){
                    this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
                    this.listWidth = w;
                    this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
                    this.restrictHeight();
                }, this);

                this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
            }
        }
    },
	expand : function(){
        if(this.isExpanded() || !this.hasFocus){
            //return;
        }
        this.list.alignTo(this.wrap, this.listAlign);
        this.list.show();
        if(Ext.isGecko2){
            this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
        }
        Ext.getDoc().on({
            scope: this,
            mousewheel: this.collapseIf,
            mousedown: this.collapseIf
        });
        this.fireEvent('expand', this);
    },
	selectAll: function() {
		this.store.each(function(record) {
			record.set(this.checkField, true);
		},this);
		this.setValue(this.getCheckedValue());
		this.doQuery(this.allQuery);
	},
	deselectAll: function() {
		this.clearValue()
	},
	assertValue: Ext.emptyFn,
	beforeBlur: Ext.emptyFn
});
Ext.reg('lovcombo', Ext.ux.form.LovCombo);


lovcombo.css文件


.ux-combo-selectall{
    padding: 3px;
}
.ux-combo-selectall-icon-checked {
    background: transparent url(../../resources/images/default/menu/checked.gif);
}


.ux-combo-selectall-icon-unchecked {
    background: transparent url(../../resources/images/default/menu/unchecked.gif);
}


.ux-lovcombo-icon-checked {
    background: transparent url(../../resources/images/default/menu/checked.gif);
}
.ux-lovcombo-icon-unchecked {
    background: transparent url(../../resources/images/default/menu/unchecked.gif);
}


.ux-combo-selectall-icon {
    text-indent: 1.8em;
    background-position: 3px 2px ! important;
    background-repeat: no-repeat ! important;
    height: 22px;
    line-height: 20px;
    font-size: 12px;
    font-weight: bold;
    -moz-user-select: none;
    cursor: pointer;
}


.ux-lovcombo-icon {
    width:16px;
    height:16px;
    float:left;
    background-position: -1px -1px ! important;
    background-repeat:no-repeat ! important;
}


 

要显示选择全部按钮修改属性 showSelectAll 为true;


示例代码:

文件名: lovcombo.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
    <script type="text/javascript" src="../../adapter/ext/ext-base.js"></script>
    <script type="text/javascript" src="../../ext-all.js"></script>
    <link rel="stylesheet" type="text/css" href="lovcombo.css" />
    <script type="text/javascript" src="lovcombo.js"></script>
    <title>无标题文档</title>
</head><body>
</body>
</html>
<script>
    var ds = new Ext.data.JsonStore({
        autoLoad: true,
        url		: "data.json",
        fields	: [
            {name: 'VALUE'},
            {name: 'TEXT'}
        ],
        root	: "datasource"
    });

    var combox = new Ext.ux.form.LovCombo({
        renderTo		: Ext.getBody(),
        store			: ds,
        mode			: "local",
        fieldLabel		: "测试",
        displayField	: "TEXT",
        valueField		: "VALUE",
        hiddenName		: "ces",
        name			: "ces",
        triggerAction	: "all",
        id				: "cc",
        //width			: 220,
        //autoSelect 		: true,
        value			: "8960,8970,8964,8965,8967,8980",
        //lazyInit		: true,
        showSelectAll	: true,
        resizable 		: true
    });
</script>


<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">测试数据:</span>

文件名:data.json

{"datasource":[{"VALUE":143360,"TEXT":"灵图软件1"},{"VALUE":143361,"TEXT":"灵图测试"},{"VALUE":8983,"TEXT":"别奇科技"},{"VALUE":8981,"TEXT":"北导科技"},{"VALUE":8982,"TEXT":"航大通讯"},{"VALUE":8984,"TEXT":"金坤老设备"},{"VALUE":8980,"TEXT":"奉节德瑞"},{"VALUE":8970,"TEXT":"四川科泰"},{"VALUE":8973,"TEXT":"重庆朝昇"},{"VALUE":8977,"TEXT":"重庆蓝盾"},{"VALUE":8961,"TEXT":"索美交通"},{"VALUE":8962,"TEXT":"广州亿程"},{"VALUE":8963,"TEXT":"德瑞科技"},{"VALUE":8964,"TEXT":"冀繁科技"},{"VALUE":8965,"TEXT":"移动车务通"},{"VALUE":8966,"TEXT":"金坤科技"},{"VALUE":8960,"TEXT":"运管企业平台"},{"VALUE":8975,"TEXT":"重庆方鼎科技"},{"VALUE":8976,"TEXT":"德瑞3G"},{"VALUE":8978,"TEXT":"宝石花"},{"VALUE":8979,"TEXT":"星软商务"},{"VALUE":8967,"TEXT":"金坤3G"},{"VALUE":8968,"TEXT":"全球鹰"},{"VALUE":8969,"TEXT":"重庆电信"},{"VALUE":8974,"TEXT":"重庆途众"},{"VALUE":8971,"TEXT":"重庆赛格"},{"VALUE":8972,"TEXT":"四川兆益"}]}


例子下载:http://download.csdn.net/detail/hahadekuai/8454417

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 29
    评论
Ext.js 3是一个JavaScript框架,用于构建Web应用程序。在Ext.js 3中,要实现多选下拉(MultiSelect Combobox),可以使用Ext.ux.form.MultiSelect组件来实现。 首先,我们需要引入相应的Ext.js文件和MultiSelect组件的文件。 ```javascript <script type="text/javascript" src="extjs/ext-all.js"></script> <script type="text/javascript" src="ext-ux/src/widgets/form/MultiSelect.js"></script> ``` 接下来,我们可以创建一个下拉框,并将其转换为多选下拉框。 ```javascript new Ext.form.MultiSelect({ fieldLabel: '多选下拉', name: 'multiselect', width: 300, height: 150, store: new Ext.data.ArrayStore({ fields: ['value', 'text'], data: [ ['1', '选项1'], ['2', '选项2'], ['3', '选项3'], ['4', '选项4'], ['5', '选项5'] ] }), valueField: 'value', displayField: 'text', mode: 'local', emptyText: '请选择', selectOnFocus: true, delimiter: ',' }); ``` 在上面的代码中,我们创建了一个MultiSelect组件,并将其放置在一个表单中。该组件的name属性用于表单提交时的字段名,width和height属性用于设置组件的宽度和高度。store属性为组件提供数据源,该数据源可以是一个数组或者一个Ext.data.Store对象。valueField属性用于指定值字段,displayField属性用于指定显示的字段。mode属性设置为'local',表示数据源来自本地数据。emptyText属性用于设置默认的空文本,selectOnFocus属性设置为true,在组件获得焦点时自动选中已选择的值。delimiter属性用于设置值之间的分隔符。 以上就是使用Ext.js 3实现多选下拉的简单示例,通过这个示例,我们可以根据实际需求进行灵活的配置和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值