跳至主要內容

checkbox

chanchaw大约 2 分钟easyui

概述

本控件必须在 form 中使用

案例

综合应用

下面 html 代码 data-options 中的 value 要根据后端数据类型设置,如果后端对应的是 boolean 则这里设置为 true,表示当勾选复选框后,表单中该属性的值是 'true',这里虽然是字符串类型,后端在反序列化时不会出错,但是如果设置 value:1 则后端会报错,提示1不可以转换为布尔类型。checked 表示默认勾选或者相反。 当复选框没有勾选时 form 表单的值是没有该属性,发送后端后该属性是 null。所以酌情在后端是否将 null 转换为 false。

<form id="form_checkbox" onsubmit="return printBadSource(this)">
  <div>
    <input id="bad_source_mill" name="bad_source_mill" class="easyui-checkbox" 
           data-options="label:'不良原因-厂家:',labelWidth:100,labelPosition:'before',
                         value:true,checked:false">
  </div>

  <div>
    <input id="bad_source_project" name="bad_source_project" class="easyui-checkbox" 
           data-options="label:'不良原因-工程内:',labelWidth:110,labelPosition:'before',
                         value:true,checked:false">
  </div>

  <div>
    <button type="submit" name="submit">打印不良原因</button>
  </div>
</form>

下面是配套 JS 代码

function printBadSource(form){
  const data = serializeObject($("#form_checkbox"));
  console.log(data);
  return false;// 阻止 form 刷新
}

function serializeObject(form) { /*将form表单内的元素序列化为对象,扩展Jquery的一个方法*/
  let o = {};
  $.each(form.serializeArray(), function (index) {
    if (o[this['name']]) {
      o[this['name']] = o[this['name']] + "," + this['value'];
    } else {
      o[this['name']] = this['value'];
    }
  });
  return o;
};

赋值

如果没有勾选则表单属性 bad_source_mill = null,所以不能直接拿该属性赋值,要通过 || 转换 null

const sourceMill = formData.bad_source_mill || false;
const sourceProject = formData.bad_source_project || false;
$('#bad_source_mill').checkbox({checked:sourceMill});
$('#bad_source_project').checkbox({checked:sourceProject});

脱离表单,单独使用控件获取值的方法: 被勾选了则返回 true,相反则返回 false

const isNetWeight = $('#netWeight').checkbox('options').checked;

获取值

返回 true 或者 false

$('#bad_source_mill').checkbox('options').checked

onChange 事件

传入参数 checked 是变更后的结果

$('#bad_source_mill').checkbox({
    onChange: function(checked){
        console.log(`bad_source_mill变更了:${checked}`);
    }
});

html 中绑定 onChange 事件的函数是无效的

<input id="myAuditTurn" class="easyui-checkbox" data-options="labelWidth:100,labelAlign:'right',checked:'true'" name="fruit" value="1" label="仅需要我审核" onChange="onChangeMyAuditTurn">

<!-- 如下也不对 -->
<input id="myAuditTurn" class="easyui-checkbox" 
       data-options="labelWidth:100,labelAlign:'right',checked:'true',onChange='onChangeMyAuditTurn'" 
       name="fruit" value="1" label="仅需要我审核" >

要采用在 js 中绑定事件的方法。