HTML radio 값 가져오기

Bluewind·2022년 5월 21일
0

Archive

목록 보기
6/6

HTML에서 radio로 체크된 값의 value를 JavaScript로 값을 받아오는 법을 알아보겠습니다.

HTML 부분

저의 프로젝트에서 HTML의 radio 부분은 아래와 같습니다.

<div class="card-body text-center"> <span class="myratings"></span>
  <fieldset class="rating">
    <input type="radio" id="star5" name="rating" value="인생 메뉴에요!" />
    <label class="full" for="star5" title="인생 메뉴에요!"></label>
    <input type="radio" id="star4" name="rating" value="또 먹고 싶어요" />
    <label class="full" for="star4" title="또 먹고 싶어요"></label>
    <input type="radio" id="star3" name="rating" value="한 번은 먹을만해요" />
    <label class="full" for="star3" title="한 번은 먹을만해요"></label>
    <input type="radio" id="star2" name="rating" value="추천하고 싶지 않아요" />
    <label class="full" for="star2" title="추천하고 싶지 않아요"></label>
    <input type="radio" id="star1" name="rating" value="완전 별로였어요" />
    <label class="full" for="star1" title="완전 별로였어요"></label>
    <input type="radio" class="reset-option" name="rating" value="reset" />
  </fieldset>
</div>

namerating으로 모두가 동일하기 때문에, HTML DOM(HTML 문서 객체 모델)인 document.getElementsByName을 통하여 아래와 같이 선택된 값을 가져와야 합니다.

JS 부분

save_review: function() {
    ...
    const rateList = document.getElementsByName("rating");
    var rate;
    rateList.forEach((node) => {
        if (node.checked) {
            rate = node.value;
        }
    })
    let data = {
        ...
        rating : rate
    };
    $.ajax({
        method: 'POST',
        url: '/api/reviews/' + foodId,
        data: JSON.stringify(data),
        contentType: 'application/json; charset=utf-8'
    ...
}

nameid와 다르게 중복 사용이 가능하기 때문에, forEach를 사용하여 node를 하나씩 돌면서 체크된 노드를 찾아서 노드의 value값을 대입해줍니다.

그리고 data에 값을 넣어줘서 ajax로 비동기통신을 완료하였습니다!

출처

profile
NO EFFORT, NO RESULTS

0개의 댓글