原生JavaScript设置、获取 单选框、复选框 的值

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
        <title>原生JavaScript设置、获取 单选框、复选框 的值</title>
    </head>
    <style type="text/css">
        label,
        input {
            cursor: pointer;
        }
    </style>

    <body>
        <label>
            <input type="radio" name="radio" value="radio0" checked /> javascript
        </label>
        <label>
            <input type="radio" name="radio" value="radio1" /> python
        </label>
        <label>
            <input type="radio" name="radio" value="radio2" /> java
        </label>
        <hr />

        <input type="button" value="设置" onclick="javascript:setValue('radio','radio2')" />
        <input type="button" value="获取" onclick="javascript:getValue('radio')" />
        <hr />

        <label>
            <input type="checkbox" name="checkbox" value="checkbox0" checked /> javascript
        </label>
        <label>
            <input type="checkbox" name="checkbox" value="checkbox1" /> python
        </label>
        <label>
            <input type="checkbox" name="checkbox" value="checkbox2" /> java
        </label>
        <hr />

        <input type="button" value="设置" onclick="javascript:setValue('checkbox','checkbox1,checkbox2')" />
        <input type="button" value="获取" onclick="javascript:getValue('checkbox')" />

        <script type="text/javascript" charset="utf-8">
            /**
             * 根据 name 获取单选框或复选框 value 
             * @param fieldName name 属性
             * @return values 字符串
             */
            function getValue(fieldName) {
                let obj = document.getElementsByName(fieldName);
                let arr = new Array();

                for (i in obj) {
                    if (obj[i].checked && !obj[i].disabled) arr.push(obj[i].value);
                }
                console.log(arr.join());
                return arr.join();
            }

            /**
             * 根据 name 和 value 设置单选框或复选框
             * @param fieldName name 属性
             * @param values 字符串
             * @return
             */
            function setValue(fieldName, values) {
                let obj = document.getElementsByName(fieldName);
                let arr = values.split(",");

                for (i in obj) {
                    obj[i].checked = "";
                    for (j in arr) {
                        if (arr[j] === obj[i].value) obj[i].checked = "checked";
                    }
                }
            }
        </script>
    </body>
</html>

 

上一篇:ASP.net:GridView控件中实现全选和全反选


下一篇:js--checked的全选,反选 ,点击子的checkbox改变父的checkbox状态