1. 程式人生 > >javascript的checkbox和radio的選中控制和取值

javascript的checkbox和radio的選中控制和取值

獲取radio的選中值(單選):

var ParentJob = $("input[name='ParentJob'][type='radio']:checked").val();

獲取checkbox的選中值(多選):

var id_array = new Array();

$('input[name="Job"][type="checkbox"]:checked').each(function () {
       id_array.push($(this).val());
});

var Job = id_array.join(',');

設定radio選中:

$(":radio[name='ParentJob'][value='" + item.ParentJob + "']").prop("checked", "checked");

設定checkbox選中:

$(":checkbox[name='Job'][value='" + item.JobID + "']").prop("checked", "checked");

radio的選擇事件

$(function () {
    $("input[type=radio][name='keqi']").change(function () { Pin(); });
});

完整例子:

<script type="text/javascript">
    $(function () {
        //重新整理
        $("#btnRefresh").click(function () {
            window.location.reload();
        });
        //儲存
        $("#btnSave").click(function () {
            //父崗位
            var ParentJob = $("input[name='ParentJob'][type='radio']:checked").val();
            if (typeof (ParentJob) == "undefined" || ParentJob == null || ParentJob == "") {
                alert("請選擇一個父崗位!");
                return;
            }
            //子崗位
            var id_array = new Array();
            $('input[name="Job"]:checked').each(function () {
                id_array.push($(this).val());//向陣列中新增元素
            });
            var Job = id_array.join(',');//將陣列元素連線起來以構建一個字串
            if (Job == "" || Job == ',') {
                alert("請選擇子崗位!");
                return;
            }
            //儲存
            $.ajax({
                url: "/Rights/Job/EditParentJob",
                data: { ParentJob: ParentJob, Job: Job, },
                success: function (data) {
                    if (data == "OK") {
                        alert("編輯成功!");
                        window.location.reload();
                    }
                    else {
                        alert(data);
                    }
                }
            });
        });
    });
    function BindChildJob(id) {       
        //清除所有子崗位勾選
        $("input[name='Job']").removeAttr("checked");
        //勾選當前父崗位所包含的子崗位
        $.ajax({
            url: "/Rights/Job/GetChildJob",
            data: { ParentJobID: id,  },
            success: function (data) {
                $.each(data, function (i, item) {
                    //alert(i);
                    //alert(item.JobID);
                    $(":checkbox[name='Job'][value='" + item.JobID + "']").prop("checked", "checked");
                });          
            }
        });
    }
</script>