HEROJOON 블로그(히로블)

Javascript Checkbox, Radio Button 사용하기 본문

Frontend

Javascript Checkbox, Radio Button 사용하기

herojoon 2020. 3. 22. 21:08
반응형

checkbox 초기값 셋팅 및 선택한 값 가져오기

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>checkbox test page</title>
</head>
<body>
    <div>
        <input type="checkbox" name="milks" value="흰우유" style="cursor:pointer;" /> 흰우유
        <input type="checkbox" name="milks" value="초코우유" style="cursor:pointer;" /> 초코우유
        <input type="checkbox" name="milks" value="딸기우유" style="cursor:pointer;" /> 딸기우유
        <input type="checkbox" name="milks" value="오디우유" style="cursor:pointer;" /> 오디우유
        <br>
        <button onclick="getCheckBoxVal()">선택한 checkbox value 가져오기</button>
        <br>
        <span id="result"></span>
    </div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // checkbox 초기값 셋팅
        $('input:checkbox[name="milks"]:input[value="초코우유"]').attr("checked", true);
        getCheckBoxVal();
    });

    // checkbox 값 가져오기
    function getCheckBoxVal() {
        var milks = []
        $("input:checkbox[name='milks']:checked").each(function(){
            milks.push(this.value)
        });
        $("#result").text("result : " + milks.toString());
    }
</script>
</body>
</html>

 

radio button 초기값 셋팅 및 선택한 값 가져오기

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>radio test page</title>
</head>
<body>
    <div>
        <input type="radio" name="milks" value="흰우유" style="cursor:pointer;" /> 흰우유
        <input type="radio" name="milks" value="초코우유" style="cursor:pointer;" /> 초코우유
        <input type="radio" name="milks" value="딸기우유" style="cursor:pointer;" /> 딸기우유
        <input type="radio" name="milks" value="오디우유" style="cursor:pointer;" /> 오디우유
        <br>
        <button onclick="getCheckBoxVal()">선택한 radio value 가져오기</button>
        <br>
        <span id="result"></span>
    </div>

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        // radio 초기값 셋팅
        $('input:radio[name="milks"]:input[value="오디우유"]').attr("checked", true);
        getCheckBoxVal();
    });

    // radio 값 가져오기
    function getCheckBoxVal() {
        var selectedRadioValue = $(':radio[name="milks"]:checked').val();
        $("#result").text("result : " + selectedRadioValue);
    }
</script>
</body>
</html>
반응형
Comments