JavaScript/jQuery

【jQuery/Selector #12】:checked

1Q74 2023. 2. 22. 10:20

1. Description

checked되어 있는 Element를 찾는다.


2. Example

#1버튼을 클릭하면 선택된 User Hobby에 따라 다르게 메시지가 표시된다.


[1q74.tistory.com] javascript/jquery/selector/:checked
User Name :
User Id :
User Hobby:
Sport Movie Game Book



[HTML Code]
[//HTML Code]

3. Code

더보기
<!-- ---------------------------------------------------------
  --
  -- Author: 1q74.tistory.com
  --
  --------------------------------------------------------- -->
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>[1q74.tistory.com] javascript/jquery/selector/:checked</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>

	<div name="_1q74-example-root">
		<div name="_1q74-example-1">
			User Name : <input type="text" name="name" value="This is user name"/>
			<br/>
			User Id : <input type="text" name="id" value="This is user id"/>
			<br/>
			User Hobby: <br/>
			<input type="checkbox" name="hobby" value="Sport"/> Sport
			<input type="checkbox" name="hobby" value="Movie"/> Movie
			<input type="checkbox" name="hobby" value="Game"/> Game
			<input type="checkbox" name="hobby" value="Book"/> Book

			<br/>
			<br/>
			<h1 id="message"></h1>
		</div>

		<div name="_1q74-example-bottom">
			<br/>
			<button name="btn-execute"/>#1. $("[name='_1q74-example-1'] :checked")</button>
		</div>
	</div>

	<hr/>
	<h5>[HTML Code]</h5>
	<div name="_1q74-source">
	</div>
	<h5>[//HTML Code]</h5>

<script>
const btnExecute = $("[name='btn-execute']");

btnExecute.click(function() {
	const checkedHobby = $("[name='_1q74-example-1'] :checked");
	const myHobbies = checkedHobby.map(function(i, el) {
		return $(el).val();
	}).get();


	const message = $("#message");	
	const hobbiesStr = myHobbies.join(", ");

	function getMessage() {
		switch(myHobbies.length) {
			case 0:
				return "My hobby is nothing. I like just thinking.";
			case 1:
				return "My hobby is " + hobbiesStr + ".";
			default:
				return "My hobbies are " + hobbiesStr + ".";
		}
	}

	message.text(getMessage());
});

// ------------------------------------------------------
// 소스출력
// ------------------------------------------------------
var textSource = $("[name='_1q74-source']");
var exampleHtml = $("[name='_1q74-example-root']").html();
var specialCharLines = textSource.text(exampleHtml).html().split("\n");

textSource.html(specialCharLines.join("<br/>").replaceAll("\t", "&nbsp;&nbsp;"));
</script>

<style>
[name|="_1q74-example"] button
,[name="_1q74-source"] button {
	background: lightgray;
	border: 5px outset;
	min-height: 30px;
}

[name|="_1q74-example"] button:active
,[name="_1q74-source"] button:active {
	border: 2px inset;
	min-height: 30px;
}
</style>
</body>
</html>

4. File

[javascript][jquery][selector]checked.html
0.00MB


5. Reference

https://api.jquery.com/checked-selector/