自己在小程序开发过程中的需求,动态新增表单元素及提交表单内容,代码如下
<index.wxml>
<view style="background:#fff">
<label class="page-label" style="width:95%;margin:0 20rpx">联系信息</label>
<block wx:for="{{formList}}" wx:key="index">
<view class="page-ul input-border" style="border:1px solid #e1e1e1;border-radius:10rpx">
<view class="page-item input-border" style="border-bottom:1px solid #f5f5f5;margin:0 20rpx">
<text class="text-color">联系人</text>
<input class="weui-input" name="names{{index}}" data-id="{{index}}" data-attr="names" type="text" placeholder="输入联系人" bindinput="customerinput"/>
</view>
<view class="page-item input-border" style="border-bottom:1px solid #f5f5f5;margin:0 20rpx">
<text class="text-color">职位</text>
<input class="weui-input" name="position{{index}}" data-id="{{index}}" data-attr="position" type="text" placeholder="输入职位" bindinput="customerinput"/>
</view>
<view class="page-item input-border" style="margin:0 20rpx">
<text class="xrequired">联系电话</text>
<input class="weui-input" name="phone{{index}}" data-id="{{index}}" data-attr="phone" type="number" placeholder="输入联系电话" bindinput="customerinput" />
</view>
</view>
</block>
<image src="../../image/additem.png" class="addcus" bindtap="additem"></image>
</view>
<index.js>
// 输入框取值
customerinput(e) {
let _this = this;
let ids = e.target.dataset.id
let attribute = e.target.dataset.attr
let Values = e.detail.value
let formi = this.data.formList[ids]
console.log(attribute, Values, formi)
if (attribute == 'names') {
formi.names = Values
} else if (attribute == 'position') {
formi.position = Values
} else {
formi.phone = Values
}
//最新的数组
this.setData({
formList: this.data.formList
})
console.log(this.data.formList, '先有数据')
},
// 新增表单
additem(e) {
let forms = this.data.formList;
var newItem = {
names: null,
position: null,
phone: null
};
let formss = forms.concat(newItem);
console.log(formss)
this.setData({
formList: formss
})
},
//提交并判断
btn(){
if (this.data.customerName&&XXX) {
let phonearr = []
this.data.formList.map(item => {
if (item.phone) {
phonearr.push(item.phone)
this.setData({
phonearr: phonearr
})
} else {
//提示信息
}
})
if (this.data.formList.length == this.data.phonearr.length) {
//接口逻辑
}
}
//css样式可以自己定义就不粘出来了
~快乐来自于分享