萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Radio 選中判斷與取值:表單驗證實戰範例 (重複內容整理版)

說明

本文內容與 ID 69926 高度重複,僅頁面結構略有不同。這裡整理為更完整的表單驗證實戰範例,並補充現代寫法。

核心邏輯 (同 69926)

// 取得選中值
var val = $('input:radio[name="groupName"]:checked').val();

// 判斷是否有選中
var isChecked = $('input:radio[name="groupName"]').is(':checked');
// 或
var hasSelection = $('input:radio[name="groupName"]:checked').length > 0;

完整表單驗證範例 (增強版)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Radio 表單驗證完整範例</title>
    <style>
        .form-group { margin-bottom: 15px; }
        label { display: inline-block; margin-right: 15px; cursor: pointer; }
        .error { color: #dc3545; font-size: 0.9em; margin-top: 5px; display: none; }
        .error.show { display: block; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
        button:hover { background: #0056b3; }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <form id="surveyForm" novalidate>
        <div class="form-group">
            <strong>1. 您的性別:</strong>
            <label><input type="radio" name="gender" value="male"> 男</label>
            <label><input type="radio" name="gender" value="female"> 女</label>
            <label><input type="radio" name="gender" value="other"> 其他</label>
            <div class="error" id="err-gender">請選擇性別</div>
        </div>
        
        <div class="form-group">
            <strong>2. 服務滿意度:</strong>
            <label><input type="radio" name="satisfaction" value="5"> 非常滿意</label>
            <label><input type="radio" name="satisfaction" value="4"> 滿意</label>
            <label><input type="radio" name="satisfaction" value="3"> 普通</label>
            <label><input type="radio" name="satisfaction" value="2"> 不滿意</label>
            <label><input type="radio" name="satisfaction" value="1"> 非常不滿意</label>
            <div class="error" id="err-satisfaction">請選擇滿意度</div>
        </div>
        
        <div class="form-group">
            <strong>3. 推薦意願 (NPS):</strong>
            <label><input type="radio" name="nps" value="promoter"> 推薦者 (9-10)</label>
            <label><input type="radio" name="nps" value="passive"> 被動者 (7-8)</label>
            <label><input type="radio" name="nps" value="detractor"> 貶損者 (0-6)</label>
            <div class="error" id="err-nps">請選擇推薦意願</div>
        </div>
        
        <button type="submit">送出問卷</button>
    </form>
    
    <script>
        $(function() {
            $("#surveyForm").on("submit", function(e) {
                e.preventDefault();
                var valid = true;
                
                // 通用驗證函式
                function validateRadio(name, errorId) {
                    var $checked = $('input:radio[name="' + name + '"]:checked');
                    var $error = $("#" + errorId);
                    if ($checked.length === 0) {
                        $error.addClass("show");
                        return false;
                    } else {
                        $error.removeClass("show");
                        return $checked.val();
                    }
                }
                
                var gender = validateRadio("gender", "err-gender");
                var satisfaction = validateRadio("satisfaction", "err-satisfaction");
                var nps = validateRadio("nps", "err-nps");
                
                if (gender && satisfaction && nps) {
                    // 收集所有資料
                    var formData = {
                        gender: gender,
                        satisfaction: parseInt(satisfaction),
                        nps: nps,
                        timestamp: new Date().toISOString()
                    };
                    console.log("表單資料:", formData);
                    alert("提交成功!\n" + JSON.stringify(formData, null, 2));
                    // 實際送出: $.post('/api/survey', formData);
                }
            });
            
            // 選中時即時清除錯誤
            $('input:radio').on('change', function() {
                $("#err-" + this.name).removeClass("show");
            });
        });
    </script>
</body>
</html>

進階:動態產生 Radio 群組

function createRadioGroup(containerId, name, options, defaultValue) {
    var $container = $("#" + containerId);
    var html = options.map(function(opt, i) {
        var checked = (opt.value == defaultValue) ? 'checked' : '';
        return '<label><input type="radio" name="' + name + '" value="' + opt.value + '" ' + checked + '> ' + opt.label + '</label>';
    }).join(' ');
    $container.html(html);
}

// 使用
createRadioGroup("genderContainer", "gender", [
    {value: "male", label: "男"},
    {value: "female", label: "女"},
    {value: "other", label: "其他"}
], "male");

原生 JS 版 (無 jQuery 依賴)

document.getElementById('surveyForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    function getRadioValue(name) {
        var selected = this.querySelector('input[name="' + name + '"]:checked');
        return selected ? selected.value : null;
    }.bind(this);
    
    var data = {
        gender: getRadioValue('gender'),
        satisfaction: getRadioValue('satisfaction'),
        nps: getRadioValue('nps')
    };
    
    var missing = Object.entries(data).filter(([k,v]) => !v).map(([k]) => k);
    if (missing.length) {
        alert("請完成以下欄位:" + missing.join("、"));
        return;
    }
    
    console.log("提交:", data);
    alert("成功!");
});

總結

Radio 群組驗證核心在於 :checked 偽類選擇器。實務建議:封裝通用驗證函式、即時清除錯誤提示、支援動態渲染、提供無依賴原生版本。本文與 ID 69926 內容重複度高,實際專案請以此增強版為主參考。

copyright © 萬盛學電腦網 all rights reserved