1. 程式人生 > >微信小程式 多選框的使用

微信小程式 多選框的使用

微信小程式 多選框的使用

需求

上個月給公司做了個OA 小程式,其中一個模組是用印申請,效果如圖所示,點選 選擇公章型別, 彈出 多選框,點選確定公章型別顯示到文字框內,再次點選可修改

效果圖

在這裡插入圖片描述在這裡插入圖片描述
在這裡插入圖片描述

核心程式碼(wxml,JavaScript)

<!-- 用印型別-彈框實現 -->
      <view class="forItemBorder">
        <!-- 用印彈窗 -->
<view class="weui-cell weui-cell_input" bindtap="showDialogBtn"> <view class="weui-cell__hd"> <view class="weui-label">公章型別</view> </view> <view style="width: 440rpx;"> <input type="text" class="weui-input"
name="sealType" value="{{sealType}}" placeholder-style="color:#B2B2B2" placeholder="請選擇公章型別" disabled="disabled" />
</view> <view class='weui-cell__ft arrow_right'></view> </view> <!-- 遮罩層 --> <view class="modal-mask"
wx:if="{{showModal}}">
</view> <!-- 彈出框 --> <view class="modal-dialog" wx:if="{{showModal}}"> <view class="modal-content"> <checkbox-group data-index="{{index}}" bindchange="checkboxChange" name="sealType"> <label class="checkbox" wx:for="{{sealTypeList}}" wx:key="key" wx:for-item="item"> <checkbox value="{{item.id}}" checked="{{item.checked}}" color="#2A98BD" /> <view class="checked_label" style="color:#37383B">{{item.gzkind}}</view> </label> </checkbox-group> </view> <!-- 操作按鈕 --> <view class="modal-footer"> <button class="btn btn-cancel" bindtap="onCancel" data-status="cancel">取消</button> <button class="btn btn-confirm" bindtap="onConfirm" data-status="confirm">確定</button> </view> </view> </view>
// 後臺傳過來的公章物件陣列用sealTypeList 接收
checkboxChange: function (e) {
	let that = this;
	let sealTypeList = this.data.sealTypeList;
	// 若之前已選擇公章,將其回顯打勾
	
	for (let i = 0; i < sealTypeList.length; i++) {
		sealTypeList[i].checked = false;
	}
	let indexes = e.detail.value;
	for (let i = 0; i < indexes.length; i++) {
		indexes[i] = parseInt(indexes[i]);
		// 多選框從1開始,陣列下標從0開始,所以需要減1
		sealTypeList[indexes[i] - 1].checked = true;
	}
	// 直接將整個list賦值回去
	this.setData({
		sealTypeList: sealTypeList
	})
},
// 使用者點選確定
onConfirm: function () {
	let that = this;
	let seals = [];
	let sealTypeList = this.data.sealTypeList;
	sealTypeList.forEach(function (e) {
		if (e.checked) {
			// gzkind是物件的一個屬性,表示具體公章型別名的字串
			seals.push(e.gzkind);
		}
	});
	// 顯示到wxml上
	this.setData({
		sealType: seals.join(",")
	})
	// 隱藏彈出的對話方塊
	//this.hideModal();
},
// 使用者點選取消
onCancel: function () {
	let that = this;
	let sealTypeList = this.data.sealTypeList;
	// 獲取上一次選擇的用印型別字串(規定用,隔開)
	let gzkind = this.data.sealType || "";
	// 放棄當前的勾選,原來誰checked,誰就checked
	sealTypeList.forEach(function (e) {
		e.checked = false;
	});
	if (gzkind !== "") {
		gzkind = gzkind.split(",");
		for (let i = 0; i < gzkind.length; i++) {
			for (let j = 0; j < sealTypeList.length; j++) {
				let e = sealTypeList[j];
				if (e.gzkind == gzkind[i]) {
					e.checked = true;
				}
			}
		}
	}

	this.setData({
		sealTypeList: sealTypeList
	});
	// 將彈出的對話方塊隱藏
	// this.hideModal();
},