Contents
see List작성일 2015. 03. 05.
JavaScript Radio 버튼 자동 체크하기
JavaScript로 라디오 버튼을 프로그래밍 방식으로 선택하는 다양한 방법입니다. 순수 JavaScript와 jQuery 방식을 모두 다룹니다.
1. HTML 구조 예시
<form id="myForm">
<input type="radio" name="gender" value="male" id="male"> 남성
<input type="radio" name="gender" value="female" id="female"> 여성
<input type="radio" name="gender" value="other" id="other"> 기타
</form>2. 순수 JavaScript 방식
// ID로 선택
document.getElementById("male").checked = true;
// querySelector로 선택
document.querySelector("#female").checked = true;
// 값으로 선택
document.querySelector("input[name=gender][value=male]").checked = true;
// name으로 모든 라디오 가져와서 선택
const radios = document.getElementsByName("gender");
radios[0].checked = true; // 첫 번째 라디오 선택
// 값으로 찾아서 선택
function selectRadioByValue(name, value) {
const radios = document.getElementsByName(name);
for (let radio of radios) {
if (radio.value === value) {
radio.checked = true;
break;
}
}
}
selectRadioByValue("gender", "female");3. jQuery 방식
// ID로 선택
$("#male").prop("checked", true);
// 값으로 선택
$("input[name=gender][value=male]").prop("checked", true);
// attr 대신 prop 사용 (jQuery 1.6+)
$("input[name=gender]:first").prop("checked", true);
// 동적으로 값 설정
const selectedValue = "female";
$("input[name=gender][value=" + selectedValue + "]").prop("checked", true);
// trigger로 change 이벤트 발생
$("input[name=gender][value=male]").prop("checked", true).trigger("change");4. 현재 선택된 값 가져오기
// 순수 JavaScript
const selected = document.querySelector("input[name=gender]:checked");
if (selected) {
console.log(selected.value);
}
// jQuery
const value = $("input[name=gender]:checked").val();
console.log(value);5. 선택 변경 이벤트
// 순수 JavaScript
document.querySelectorAll("input[name=gender]").forEach(radio => {
radio.addEventListener("change", function() {
console.log("선택됨:", this.value);
});
});
// jQuery
$("input[name=gender]").on("change", function() {
console.log("선택됨:", $(this).val());
});6. 동적 라디오 버튼 생성 및 선택
// 동적 생성
const options = ["옵션1", "옵션2", "옵션3"];
const container = document.getElementById("container");
options.forEach((opt, idx) => {
const radio = document.createElement("input");
radio.type = "radio";
radio.name = "dynamic";
radio.value = opt;
radio.id = "opt" + idx;
const label = document.createElement("label");
label.htmlFor = "opt" + idx;
label.textContent = opt;
container.appendChild(radio);
container.appendChild(label);
});
// 첫 번째 자동 선택
document.querySelector("input[name=dynamic]").checked = true;7. 폼 제출 시 검증
// 선택 여부 확인
function validateRadio() {
const selected = document.querySelector("input[name=gender]:checked");
if (!selected) {
alert("성별을 선택해주세요");
return false;
}
return true;
}
// 폼 제출
document.getElementById("myForm").addEventListener("submit", function(e) {
if (!validateRadio()) {
e.preventDefault();
}
});attr vs prop 차이
| 메서드 | 용도 | 예시 |
|---|---|---|
| attr() | HTML 속성 | 초기값 |
| prop() | DOM 속성 | 현재 상태 (권장) |
주의사항
- jQuery 1.6+에서는 checked에 prop() 사용
- change 이벤트는 사용자 클릭 시만 발생
- 프로그래밍 변경 시 trigger("change") 필요
javascript
| No | 작성일 | Title |
|---|---|---|
| 2213 | 2026. 02. 11. | React Server Components 심화 패턴과 활용 |
| 2212 | 2026. 02. 11. | Next.js 15 App Router 완벽 가이드 |
| 2171 | 2026. 02. 11. | Astro vs Remix vs SvelteKit: 풀스택 프레임워크 비교 |
| 2170 | 2026. 02. 11. | 프론트엔드 테스트 전략: Vitest + Testing Library + Playwright |
| 2169 | 2026. 02. 11. | React 19 신기능: use(), Actions, 서버 컴포넌트 개선 |
| 2168 | 2026. 02. 11. | Web API 최신 트렌드: View Transitions, Popover, Container Queries |
| 2167 | 2026. 02. 11. | Vite 6.0: 차세대 프론트엔드 빌드 도구 |
| 2166 | 2026. 02. 11. | Tailwind CSS 4.0과 모던 CSS 프레임워크 동향 |
| 2165 | 2026. 02. 11. | Zustand vs Jotai vs Recoil: React 상태 관리 비교 2025 |
| 2164 | 2026. 02. 11. | TypeScript 5.x 신기능과 타입 시스템 고급 활용 |