Use of Layui Switch

Posted by matthewdingley on Fri, 04 Oct 2019 10:37:49 +0200

Use layui switch in Jsp list page

  1. Functional introduction:
    The layui switch is used to control the state of a data. 0: Enables 1: Disables.

  2. Background framework:
    SpringMVC+Mybatis

  3. Background page:
    Jsp page

  4. Functional Display:

  5. Code implementation:
    Reception:

<tbody>
		<c:forEach items="${resultMap.result.records }" var="r">
				<tr>
					<td>
						<input type="checkbox" name="ids" lay-skin="primary">
					</td>
					<td>${r.code }</td>
					<td>${r.payments }</td>
					<td>${r.raised }</td>
					<td>${r.createTime }</td>
					<td>
						<input type="checkbox" value="0" name="state" lay-skin="switch" lay-text="Enable|Prohibit" ${r.state eq '0' ? 'checked': '' }>
						<input type="hidden" id="kaigID" value="${r.id }" />
					</td>
				</tr>
			</c:forEach>
		</tbody>

Front desk JS:

<script>
		layui.use('form', function() {
			var form = layui.form; //form
			form.on('switch', function(data) {
				console.log(data.elem.checked); //Whether the switch is on, true or false
				console.log(data.value); //Switch value can also be obtained by data.elem.value
				var id = $(data.othis).next("input").val();
				if(data.elem.checked == true) {
					$.ajax({
						type: "post",
						async: false,
						data: "id=" + id + "&state=" + 0,
						url: "changeState",
						success: function(data) {
							flag = data
						},
					});
					if(flag == "Ny") {
						layer.msg("No more than three enabled States!");
					} else {
						layer.msg("Enabled!");
					}
				} else {
					$.ajax({
						type: "post",
						async: false,
						data: "id=" + id + "&state=" + 1,
						url: "changeState",
						success: function(data) {
							flag = data
						},
					});
					if(flag == "yes") {
						layer.msg("disabled!");
					}  
				}

			});
		})
	</script>

When the switch is clicked, the callback function returns an object parameter with two members:

form.on('switch(filter)', function(data){
  console.log(data.elem); //Get the checkbox original DOM object
  console.log(data.elem.checked); //Whether the switch is on, true or false
  console.log(data.value); //Switch value can also be obtained by data.elem.value
  console.log(data.othis); //Get beautified DOM objects
});  

js to be introduced

<script src="layui/layui.js></script>

Functional logic:
When you click on the switch, js gets the ID of the current data, layui switches listen for events and return true/false. My function is to set the status to 0 when you return true, carry the ID and status code to the background processing using Ajax, and vice versa, set the status to 1 when you return true.

Topics: JSP Mybatis