개요 : 체크박스나 라디오버튼 태그 중에 선택되어 있는 요소를 찾습니다.
- jQuery(':checked')
:checked 는 checkbox 나 radio buttons 들에 해당됩니다. 콤보(select) 박스는 :selected 선택자를 사용하세요.
예 제
체크박스를 클릭할 때마다 그 상태를 체크하여 만일 선택(체크)상태이면 체크된 상태인 개수를 알려줍니다.
<!DOCTYPE html> <html> <head> <style> div { color:red; } </style> <script src="http://code.jquery.com/jquery-1.4.4.js"></script> </head> <body> <form> <input type="checkbox" name="newsletter" checked="checked" value="Hourly" /> <input type="checkbox" name="newsletter" value="Daily" /> <input type="checkbox" name="newsletter" value="Weekly" /> <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> <input type="checkbox" name="newsletter" value="Yearly" /> </form> <div></div> <script> function countChecked() { var n = $("input:checked").length; $("div").text(n + (n <= 1 ? " is" : " are") + " checked!"); } countChecked(); $(":checkbox").click(countChecked); </script> </body> </html>
미리보기
위 소스중에 보시면 n <= 1 ? " is" : " are" 의 구문이 있습니다. 삼항식이 안에 있습니다. 삼항식이란
"조건 ? 참일 때 : 거짓일때"
의 구문입니다. 위에서는 n 이 1보다 작거나 같을 때 " is" 를 출력하고, 1보다 클 때 " are" 를 출력합니다.
우리가 쉽게 볼 수 있는 if ~ else 로 표현하면
if(n <= 1) a = " is"; else a = " are";