微信小程序day03_03之form组件的提交和重置
一. form表单
form
表单,将组件内的用户输入的<switch> <input> <checkbox> <slider> <radio> <picker>
提交。
当点击 表单中 form-type 为 submit 的 组件时,会将表单组件中的 value 值进行提交,需要在表单组件中加上 name 来作为 key。
主要用到的属性为如下的两个:
可与button配合使用, button有form-type
的属性, 用于表单的提交和重置事件
二.checkbox-group的bindchange事件演示
在wxml中代码如下
<checkbox-group bindchange="changed">
<checkbox value="中国">中国 </checkbox>
<checkbox value="日本" disabled='true'>日本 </checkbox>
<checkbox value="美国" checked='true' color='red'>美国 </checkbox>
</checkbox-group>
在js中的代码如下
changed: function(e){
debugger;
}
当在页面中,进行点击checkbox-group
的多选框时,会进入debug模式
如下图所示 :
在其右边的watch中,点击加号,输入e这个变量,可以观察其值.
输入e.detail.value
, 可以观察选中的多选框的数组的值, 可以看到是一个长度为2的数组
三.表单的提交和重置代码演示
在wxml中代码如下, 整个代码使用form
标签进行嵌套, 使用bindsubmit
属性,进行表单提交事件的绑定.
使用bindreset
属性, 进行formReset
表单重置的绑定.
表单中, 定义了两个checkbox-group
, 其中name
分别为aa和bb, 该name属性, 用于指定表单提交的key值.
并且在底部, 定义了两个button, form-type
属性分别指定为了submit和reset, 用于表单的提交和重置.
<form bindsubmit='formSubmit' bindreset='formReset'>
<checkbox-group name="aa" bindchange="changed">
<checkbox value="中国">中国 </checkbox>
<checkbox value="日本" disabled='true'>日本 </checkbox>
<checkbox value="美国" checked='true' color='red'>美国 </checkbox>
</checkbox-group>
<checkbox-group name="bb">
<label wx:for='{{array}}' wx:key="userInfoListId">
<checkbox id='{{item.id}}' value='{{item.name}}'
checked='{{item.checked}}' color='{{item.color}}'
disabled='{{item.disabled}}' /> {{item.value}}
</label>
</checkbox-group>
<button form-type='submit'>提交</button>
<button form-type='reset'>重置</button>
</form>
在js中的代码如下.
主要是定义了formSubmit
表单提交和formReset
表单重置的函数
// pages/myform/myform.js
Page({
/**
* 页面的初始数据
*/
data: {
array: [
{
id: "1001", name: "中国", value: "中国", checked: false, color: "red", disabled: false, sdf: "sdfsd"
},
{
id: "1002", name: "日本", value: "日本", checked: true, color: "red", disabled: false, sdfsdf: "sfsdfd"
},
{
id: "1003", name: "美国", value: "美国", checked: true, color: "red", disabled: false, sdf55sdf: "sdfsdfdf"
}
]
},
changed: function(e){
} ,
formSubmit: function(e){
debugger;
console.log("数据已经被提交了");
},
formReset: function(e){
console.log("数据已经被重置了");
}
})
页面中显示如下
当点击 重置时, 控制台打印如下 : 代表成功触发了表单重置的formReset
函数
并且所有选中的框,都会变成未选中的状态
当在页面中,点击如下的按钮, 当点击提交时,
进入debug模式, 可以看到在e.detail.value
中,已经有两个数组了,第一个数组aa为第一个checkbox-group
选中的值为美国.
第二个数组bb为第二个checkbox-group
选中的值为美国和日本.
官方文档: https://developers.weixin.qq.com/miniprogram/dev/component/form.html