1. 라디오 버튼 값 가져오기 및 설정하기
<!-- 라디오 버튼 -->
<ul type="none">
<li><input type="radio" name="fruit" value="apple" checked="checked"/>사과</li>
<li><input type="radio" name="fruit" value="pear"/>배</li>
<li><input type="radio" name="fruit" value="banana"/>바나나</li>
</ul>
<button type="button" id="choice">선택</button>
<script type="text/javascript">
$("#choice").click(function(){
// Getter: 선택된 라디오 버튼의 값을 가져오기
let fruit = $("input[name='fruit']:checked").val();
alert(fruit); // 현재 선택된 과일 출력
// Setter: 특정 라디오 버튼 선택하기
$("input[name='fruit']").val(['banana']);
});
</script>
설명 :
** 라디오 버튼 값 가져오기 (getter) **
: $("input[name='fruit']:checked").val();
- name='fruit' 속성을 가진 <input> 중에서 :checked(체크된) 요소의 값을 가져온다.
** 라디오 버튼 값 설정하기 (setter) **
: $("input[name='fruit']").val(['banana']);
- "banana" 값을 가진 라디오 버튼을 선택한다.
2. 체크박스 값 가져오기 및 설정하기
<!-- 체크박스 -->
<input type="checkbox" id="chk1" name="chk1"/>그림그리기
<input type="checkbox" id="chk2" name="chk2"/>음악감상
<br/><br/>
<button type="button" id="hobby">check</button>
<script type="text/javascript">
$("#hobby").click(function(){
// Getter: 체크 여부 확인
let check1 = $("#chk1").is(":checked");
alert(check1); // true(체크됨) 또는 false(체크 안됨)
});
</script>
설명 :
** 체크박스 체크 여부 확인 (getter) **
: $("#chk1").is(":checked");
- #chk1 체크박스가 체크되어 있으면 true, 아니면 false 반환
** 체크박스 값 설정하기 (setter) **
: 체크박스를 선택하거나 해제할 때는 .prop()을 사용해야 한다.
$("#chk1").prop("checked", true); // 체크박스 체크하기
$("#chk1").prop("checked", false); // 체크 해제하기
3. JavaScript 코드 비교
라디오 버튼 값 가져오기
let fruit = document.querySelector("input[name='fruit']:checked").value;
console.log(fruit);
라디오 버튼 값 설정하기
document.querySelector("input[name='fruit'][value='banana']").checked = true;
체크박스 값 가져오기
let isChecked = document.getElementById("chk1").checked;
console.log(isChecked);
체크박스 값 설정하기
document.getElementById("chk1").checked = true; // 체크박스 체크
document.getElementById("chk1").checked = false; // 체크 해제
'Front > jQuery' 카테고리의 다른 글
jQuery) HTML 속성과 스타일 조작 : .css(), .attr(), .prop(), .addClass(), removeClass(), toggleClass() (0) | 2025.02.27 |
---|---|
jQuery) 테이블의 행과 셀에 이벤트 추가하는 기능 예제 (0) | 2025.02.26 |
jQuery) 태그 선택 / 클래스 변경 / 요소 숨기기, 보이기 / 스타일 적용 방법 (0) | 2025.02.26 |
jQuery)이벤트 처리와 요소 조작 : 클릭 이벤트 / 입력 값 가져오기 / 요소 삭제 (0) | 2025.02.26 |
jQuery) 기본 개념 및 사용법 (0) | 2025.02.26 |