日期:2014-05-17  浏览次数:20400 次

jquery 根据条件设置checkbox 默认选中


HTML code

<script type="text/javascript">
        $(document).ready(function () {
            var vClassID = $("#ddlClassID").val();
            if (vClassID > 0) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json",
                    url: "/webservices/common.asmx/GetTags",
                    data: "{ClassID:'" + vClassID + "'}",
                    dataType: 'json',
                    success: function (result) {
                        var s = result.d;
                        $("#tags").html(s);
                    }
                });
            }
            var tags = $("#hidTags").val();


            $("#ddlClassID").change(function () {
                if ($(this).val() > 0) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "/webservices/common.asmx/GetTags",
                        data: "{ClassID:'" + $(this).val() + "'}",
                        dataType: 'json',
                        success: function (result) {
                            var s = result.d;
                            $("#tags").html(s);
                        }
                    });
                }
            });
        });
        
    </script>



HTML code

<asp:DropDownList ID="ddlClassID" runat="server">
</asp:DropDownList>
<span id="tags"></span>
<input type="hidden" name="hidTags" id="hidTags" value="aaa,ccc" />




common.asmx返回如下
<span><input type='checkbox' name='cbTag' value='aaa' />aaa </span>
<span><input type='checkbox' name='cbTag' value='bbb' />bbb</span>
<span><input type='checkbox' name='cbTag' value='ccc' />ccc </span>


获取hidTags的值 为aaa,ccc 设置checkbox默认选中 aaa,ccc


------解决方案--------------------
JScript code
 var items = $("#hidTags").val().split(/[,,]/g);
            $.each(items, function (index, item) {
                $("input[name='cbTag']").each(function () {
                    if ($(this).val() == item) {
                        $(this).attr("checked",true);
                    }
                });
            });

------解决方案--------------------
你不能写到success: function (result) {}外面,写到外面就是错误的了