CheckBox
์ฒดํฌ ๋ฐ์ค ํ๊ทธ์ ์์ฑ์ ์ฐ์ตํ UI์ด๋ค.
<body>
<div id = "red">red</div>
<div id = "yellow">yellow</div>
<div id = "blue">blue</div>
<div id = "black">black</div>
<div id = "base">
<form>
<input type = "checkbox" name = "all" onclick = "allSel(this)"/>์ ์ฒด์ ํ<br/> <!-- this๋ ํฌํจํ๊ณ ์๋ ์ธํ ๊ฐ์ฒด๋ฅผ ๋งํจ -->
<input type = "checkbox" name = "chk" value = "red" />๋ ๋์ ํ<br/>
<input type = "checkbox" name = "chk" value = "yellow" />์๋ก์ฐ์ ํ<br/>
<input type = "checkbox" name = "chk" value = "blue" />๋ธ๋ฃจ์ ํ<br/>
<input type = "checkbox" name = "chk" value = "black" />๋ธ๋์ ํ<br/>
<button type = "button" onclick = "sel()">์ ํ</button>
<button type = "button" onclick = "clearDiv()">์ด๊ธฐํ</button> </form>
</div>
</body>
์ด๋ ๊ฒ ๋ง๋ค๋ฉด ๋๊ณ CSS๋ก ์์ ํด์ค๋ค. CSS๋ ์๋ตํ๊ฒ ๋ค. ์ ์ฒด์ ํ ๋ฒํผ์์ allSel(this)๋ฅผ ํด๋ฆญํ ๋ ํธ์ถ์ ํ๋๋ฐ ์ด this๋ input์์๋ฅผ ๋งํ๋ค. ์ฆ input์์์ ๋ด์ฉ์ ์ ๋ฌํ๊ฒ ๋ค๋ ๋ป์ด๋ค.
function allSel(chkAllObj){
console.log(chkAllObj.checked); // ์ ์ฒด์ ํ ์ฒดํฌ๋ฐ์ค์ ์ฒดํฌ์ฌ๋ถ ํ์ธ ๊ฐ๋ฅ
var chks = document.getElementsByName("chk"); //[ehk,ehk,ehk,ekh]
chks.forEach((chk) =>{
chk.checked = chkAllObj.checked;
}
);
}
์ด๊ฐ allSel ํจ์์ด๋ค. ํธ์ถ์ ํ input์์๋ฅผ ์ ๋ฌ ๋ฐ์ ๋๋ง๋ค ์ฝ์์ ์ฒดํฌ๊ฐ ํ๋ ธ๋์ง ๋์๋์ง true/false๋ก ๋ฐํํ๋ค.
๊ทธ๋ฆฌ๊ณ DOM ํ์์ผ๋ก Name์ด chk์ธ๊ฒ์ ์ฐพ์์ chks๋ผ๋ ๋ฐฐ์ด์ ๋ฃ์ด์ฃผ๊ณ ๋ฐฐ์ด์ for๋ฌธ์ ํตํด์ ์ ์ฒด์ ํ์ true/false์ฌ๋ถ๋ฅผ ๊ฐ๊ฐ์ ๋ฃ์ด์ค๋ค.
function sel(){
//์ฒดํฌ๋ฐ์ค ์ฌ๋ฌ๊ฐ ํ์
var chks = document.getElementsByName("chk");
chks.forEach((chk) =>
{
if(chk.checked){
document.getElementById(chk.value).style.backgroundColor=chk.value;
}else{
document.getElementById(chk.value).style.backgroundColor="white"
}
})
}
์ด ๋ถ๋ถ์ ๊ฐ๊ฐ์ ์ฒดํฌ๋ฐ์ค์ ์๋ฐ์คํฌ๋ฆฝํธ ์ฝ๋์ด๋ค.
if ๋ฌธ๋ถํฐ ์ค๋ช ์ ํ์๋ฉด chk.value ๊ฐ์ด id์ ์ผ์นํ๋ ๋ถ๋ถ์ ์ฐพ๋๋ค. ๊ทธ ๋ถ๋ถ์ ์ฐพ์์ ํด๋น ๊ทธ ๊ตฌ์ญ์ value์ ๋ช ์๋ ๊ฐ์ผ๋ก ๋ฐ๊ฟ์ค๋ค.