input checkbox反選框

input checkbox 反選, 全選, 反選demo

<!DOCTYPE html>
<html>
<head>
	<title>input反選框練習</title>
	<style type="text/css">
		* {
			padding: 0px;
			margin: 0px;
		}
		.box {
			margin: 150px auto;
			height: 300px;
			width: 300px;
			left: 100px;
		}
		.check1 {
			width: 20px;
			height: 20px;
		}
		.box label {
			margin-left: 20px;
		}
		.checkbox {
			padding-top: 20px;
		}
	</style>
</head>
<body>

<div class="box">
	<label for="ch1">  選1
		<input type="checkbox" name="check" id="ch1" class="check1"> 
	</label>
	<label for="ch2">  選2
		<input type="checkbox" name="check" id="ch2" class="check1"> 
	</label>
	<label for="ch3">  選3
		<input type="checkbox" name="check" id="ch3" class="check1"> 
	</label>
	<label for="ch4">  選4
		<input type="checkbox" name="check" id="ch4" class="check1" checked> 
	</label>

	<div class="checkbox">
		<button class="reset">取消選擇</button>
		<button class="chiose_all">全選</button>
		<button class="inverse">反選</button>
	</div>

</div>

<script type="text/javascript" src="../js/jquery-3.3.1.js"></script>
<script type="text/javascript">
	$(function(){
		function pass(nthis){
			$(nthis).removeAttr('checked')
		}
		function chiose(nthis){
			$(nthis).attr('checked','True')
		}

		// 點擊checkbox的時先添加一個 checked屬性,
		$('input[type="checkbox"]').on('click', function(){
			if ($(this).attr('checked')) {
				pass(this)
			} else {
				chiose(this)
			}
		})

		// 全部取消
		$(".checkbox button.reset").on('click', function(){
			$('.box input[type="checkbox"]').each(function(){
				pass(this)
			})
		})

		// 全選
		$("button.chiose_all").on('click', function(){
			$('.box input[type="checkbox"]').each(function(){
				chiose(this)
			})
		})

		// 反選 
		$("button.inverse").on('click', function(){
			// 先循環帶有input的框
			$(".box input").each(function(){
				// 如果input框有checked這個屬性
				if ($(this).attr('checked')) {
				// 就直接先刪除checked
					pass(this)
				}else{
				// 然後添加其它
					chiose(this)
				}
			})
		})


	})

</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章