Skip to content

Instantly share code, notes, and snippets.

@johnny12150
Last active July 8, 2021 16:36
Show Gist options
  • Save johnny12150/dc9b7cd4f97f0ad56f5f9c2814168671 to your computer and use it in GitHub Desktop.
Save johnny12150/dc9b7cd4f97f0ad56f5f9c2814168671 to your computer and use it in GitHub Desktop.
ty js 101 count selected boxes
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Choose your seats</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
</head>
<body>
<h1>Select max three seats</h1>
<div id='seats'>
<input type="checkbox" class="seat">
<input type="checkbox" class="seat">
<input type="checkbox" class="seat">
<input type="checkbox" class="seat">
<input type="checkbox" class="seat">
</div>
</body>
<script>
// jquery style
var limit = 3;
/*$('input.seat').on('change', function(evt) {
if($(this).siblings(':checked').length >= limit) {
alert('超過上限');
this.checked = false;
}
});*/
// pure js
var seats_area = document.getElementById('seats');
// addEventListener doesn't support 'on' prefix such as onclick
// https://www.w3schools.com/jsref/event_onclick.asp
seats_area.addEventListener('click', check_seats);
var seats = document.getElementsByClassName('seat');
// https://roytuts.com/limit-number-of-checkbox-selections-using-javascript/
function check_seats(){
var checked_count = 0;
for (var i = 0; i < seats.length; i++) {
checked_count += (seats[i].checked)
}
console.log(checked_count);
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment