Enable Disable Bootstrap SelectPicker DropDownList using jQuery in ASP.Net

Last Reply 5 months ago By dharmendr

Posted 5 months ago

Hi,

I am running into an issue with attempting to enable and disable a dropdownlist based on a checkbox control.

When I load an asp page using server side disable for dropdownlists that have the checkbox marked already. I am not able to enable these dropdownlists when I uncheck the checkbox using jquery.

Oddly, I am able to enable and disable dropdownlists that are not disabled server side. I believe this might have something to do with the class: aspnetdisabled being applied to the server side dropdownlists.

When the cssclass for the dropdownlist includes "selectpicker" the functionality no longer works. 

Is this something you are able to review?

In my rowdatabound: (VB.net)

            'Marked items set to disabled
            If e.Row.Cells(11).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked Then
                e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Enabled = False
                e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Visible = True
                e.Row.Cells(7).Controls.OfType(Of Label)().FirstOrDefault().Visible = True
                e.Row.Cells(9).Controls.OfType(Of TextBox)().FirstOrDefault().Enabled = False
                e.Row.Cells(12).Controls.OfType(Of CheckBox)().FirstOrDefault().Enabled = False
                btnAddLoan.Enabled = False
            End If

Gridview: 

        <asp:GridView ID="gvtfaTrust" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="20" AllowSorting="True" OnPageIndexChanging="OnPageIndexChanging" OnSorting="OnSorting" EnableViewState="true" OnRowDataBound="gvtfaTrust_RowDataBound"  CssClass="table table-striped table-bordered table-hover" DataKeyNames="ID" Width="98%" HorizontalAlign="Center">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="0. ID" ShowHeader="false" HeaderStyle-Wrap="false" SortExpression="ID" />                
                <asp:TemplateField HeaderText="7. GL Account" HeaderStyle-HorizontalAlign="Left" SortExpression="GLAcct">
                    <ItemTemplate>
                        <asp:Label ID="LabelGLAcct" runat="server" Text='<%# Eval("GLAcct") %>' Visible="false"></asp:Label>
                        <asp:DropDownList ID="DropdownlistGLAcct" runat="server" visible="false" CssClass="selectpicker show-tick form-control Update" data-style="btn btn-default btn-sm" data-live-search-style="true" data-live-search="true"/>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Left" Wrap="false" />
                </asp:TemplateField>
                <asp:BoundField DataField="Amount" HeaderText="8. Amount" DataFormatString="{0:C}" HeaderStyle-Wrap="false" SortExpression="Amount" />
                <asp:TemplateField HeaderText="9. Exchange" SortExpression="ExchangeRate">
                    <ItemTemplate>
                        <asp:Label ID="LabelExchangeRate" runat="server" Text='<%# String.Format("{0:0.00000}", Eval("ExchangeRate")) %>' visible="false"></asp:Label>
                        <asp:TextBox runat="server" ID="TextExchangeRate" Text='<%# Eval("ExchangeRate", "{0:0.00000}") %>' CssClass="btn-sm form-control Update" Width="65px" Enabled='<%# Eval("IsExchangeRate") %>' data-mask="#.##000"/>
                    </ItemTemplate>
                    <HeaderStyle Wrap="False" />
                </asp:TemplateField>
                <asp:TemplateField HeaderText="10. Details" HeaderStyle-Wrap="false" SortExpression="details">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnSelect" runat="server" Text='<%# Eval("Details") %>' CommandName="Select" CommandArgument="<%# Container.DataItemIndex %>"/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="11. Mark" HeaderStyle-Wrap="false" SortExpression="Marked">
                    <ItemTemplate>
                        <asp:Checkbox ID="btnMark" runat="server" Checked='<%# Eval("Marked") %>' CssClass="form-check-input Mark"/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="12. Ignore" HeaderStyle-Wrap="false" SortExpression="Ignore">
                    <ItemTemplate>
                        <asp:Checkbox ID="btnIgnore" runat="server"  AutoPostBack="true" Checked='<%# Eval("Ignore") %>' OnCheckedChanged="Ignore_Click"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
       </asp:GridView>

Javascript: 

        $(function () {
            $('.Mark').on('change', function () {
                var id = $(this).closest('tr').find('td').eq(0).html();
                var checkbox = $(this).closest('tr').find('[id*=btnMark]');
                var Marked = $(this).closest('tr').find('[id*=btnMark]:checked').val();
                var DropdownlistGLAcct = $(this).closest('tr').find('[id*=DropdownlistGLAcct]');
                var LabelGLAcct = $(this).closest('tr').find('[id*=LabelGLAcct]');
                var TextExchangeRate = $(this).closest('tr').find('[id*=TextExchangeRate]');
                var LabelFullname = document.getElementById('<%=LabelFullname.ClientID%>').innerText;

                $.ajax({
                    type: "POST",
                    url: "MOGP_Application.aspx/Mark",
                    data: "{id:" + id + ",Marked:'" + Marked + "', LabelFullname:'" + LabelFullname + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("get session failed " + errorThrown);
                    },
                    success: function (response) {
                        if (response.d == "failed") {
                            $(checkbox).prop('checked', false);
                        }
                        if (response.d == "success") {
                            //alert($(checkbox).prop('checked'));
                            if ($(checkbox).prop('checked') == false) {
                                $(TextExchangeRate).prop("disabled", false);
                                $(DropdownlistGLAcct).prop("disabled", false);
                            }
                            if ($(checkbox).prop('checked') == true) {
                                $(TextExchangeRate).prop("disabled", true);
                                $(DropdownlistGLAcct).prop("disabled", true);
                            }
                        }
                    }
                });
            });
        });

 

Posted 5 months ago Modified on 5 months ago

Hi Warren,

Refer the modified code.

HTML

<asp:Label ID="LabelFullname" Text="Test" runat="server" />
<asp:GridView ID="gvtfaTrust" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvtfaTrust_RowDataBound"
    DataKeyNames="ID">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="0. ID" ShowHeader="false" HeaderStyle-Wrap="false"
            SortExpression="ID" />
        <asp:BoundField DataField="BankAccount" HeaderText="1. Bank Account" HeaderStyle-Wrap="false"
            SortExpression="BankAccount" Visible="false" />
        <asp:BoundField DataField="DateDeposited" HeaderText="2. Date Deposited" DataFormatString="{0:dd, MMM yyyy}"
            HeaderStyle-Wrap="false" SortExpression="DateDeposited" />
        <asp:BoundField DataField="PayName" HeaderText="3. Payee" HeaderStyle-Wrap="false"
            SortExpression="PayName" />
        <asp:BoundField DataField="Reference" HeaderText="4. Reference" HeaderStyle-Wrap="false"
            SortExpression="Reference" />
        <asp:BoundField DataField="Memo" HeaderText="5. Memo" HeaderStyle-Wrap="false" SortExpression="Memo" />
        <asp:BoundField DataField="EntryType" HeaderText="6. Entry Type" HeaderStyle-Wrap="false"
            SortExpression="EntryType" />
        <asp:TemplateField HeaderText="7. GL Account" HeaderStyle-HorizontalAlign="Left"
            SortExpression="GLAcct">
            <ItemTemplate>
                <asp:Label ID="LabelGLAcct" runat="server" Text='<%# Eval("GLAcct") %>' Visible="false"></asp:Label>
                <asp:DropDownList ID="DropdownlistGLAcct" runat="server" Visible="false" CssClass="selectpicker show-tick form-control Update"
                    data-style="btn btn-default btn-sm" data-live-search-style="true" data-live-search="true">
                    <asp:ListItem Text="text 1" />
                    <asp:ListItem Text="text 2" />
                </asp:DropDownList>
            </ItemTemplate>
            <HeaderStyle HorizontalAlign="Left" Wrap="false" />
        </asp:TemplateField>
        <asp:BoundField DataField="Amount" HeaderText="8. Amount" DataFormatString="{0:C}"
            HeaderStyle-Wrap="false" SortExpression="Amount" />
        <asp:TemplateField HeaderText="9. Exchange" SortExpression="ExchangeRate">
            <ItemTemplate>
                <asp:Label ID="LabelExchangeRate" runat="server" Text='<%# String.Format("{0:0.00000}", Eval("ExchangeRate")) %>'
                    Visible="false"></asp:Label>
                <asp:TextBox runat="server" ID="TextExchangeRate" Text='<%# Eval("ExchangeRate", "{0:0.00000}") %>'
                    CssClass="btn-sm form-control Update" Width="65px" Enabled='<%# Eval("IsExchangeRate") %>'
                    data-mask="#.##000" />
            </ItemTemplate>
            <HeaderStyle Wrap="False" />
        </asp:TemplateField>
        <asp:TemplateField HeaderText="10. Details" HeaderStyle-Wrap="false" SortExpression="details">
            <ItemTemplate>
                <asp:LinkButton ID="btnSelect" runat="server" Text='<%# Eval("Details") %>' CommandName="Select"
                    CommandArgument="<%# Container.DataItemIndex %>" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="11. Mark" HeaderStyle-Wrap="false" SortExpression="Marked">
            <ItemTemplate>
                <asp:CheckBox ID="btnMark" runat="server" Checked='<%# Eval("Marked") %>' CssClass="form-check-input Mark" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="12. Ignore" HeaderStyle-Wrap="false" SortExpression="Ignore">
            <ItemTemplate>
                <asp:CheckBox ID="btnIgnore" runat="server" AutoPostBack="true" Checked='<%# Eval("Ignore") %>'
                    OnCheckedChanged="Ignore_Click" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
    <SelectedRowStyle BackColor="lightyellow" />
    <PagerSettings Mode="NumericFirstLast" />
    <PagerStyle CssClass="pagination-ys" HorizontalAlign="Left" />
</asp:GridView>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('.Mark').on('change', function () {
            var id = $(this).closest('tr').find('td').eq(0).html();
            var checkbox = $(this).closest('tr').find('[id*=btnMark]');
            var Marked = $(this).closest('tr').find('[id*=btnMark]:checked').val();
            var DropdownlistGLAcct = $(this).closest('tr').find('[id*=DropdownlistGLAcct]');
            var LabelGLAcct = $(this).closest('tr').find('[id*=LabelGLAcct]');
            var TextExchangeRate = $(this).closest('tr').find('[id*=TextExchangeRate]');
            var LabelFullname = document.getElementById('<%=LabelFullname.ClientID%>').innerText;
            $.ajax({
                type: "POST",
                url: "Default.aspx/Mark",
                data: "{id:" + id + ",Marked:'" + Marked + "', LabelFullname:'" + LabelFullname + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("get session failed " + errorThrown);
                },
                success: function (response) {
                    if (response.d == "failed") {
                        $(checkbox).prop('checked', false);
                        $(DropdownlistGLAcct).prop("disabled", false);
                        $(DropdownlistGLAcct).closest('td').find('button').removeClass('disabled');
                    }
                    else {
                        if ($(checkbox).prop('checked') == false) {
                            $(TextExchangeRate).prop("disabled", false);
                            $(DropdownlistGLAcct).prop("disabled", false);
                            $(DropdownlistGLAcct).closest('td').find('button').removeClass('disabled');
                        }
                        else {
                            $(TextExchangeRate).prop("disabled", true);
                            $(DropdownlistGLAcct).prop("disabled", true);
                            $(DropdownlistGLAcct).closest('td').find('button').addClass("disabled");
                        }
                    }
                }
            });
        });
    });
</script>

Namespaces

C#

using System.Data;
using System.Web.Services;

VB.Net

Imports System.Data
Imports System.Web.Services

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { 
            new DataColumn("ID", typeof(int)), 
            new DataColumn("BankAccount", typeof(string)), 
            new DataColumn("DateDeposited", typeof(string)), 
            new DataColumn("PayName", typeof(string)), 
            new DataColumn("Reference", typeof(string)), 
            new DataColumn("Memo", typeof(string)), 
            new DataColumn("EntryType", typeof(int)), 
            new DataColumn("GLAcct", typeof(string)), 
            new DataColumn("Amount", typeof(int)), 
            new DataColumn("ExchangeRate", typeof(int)), 
            new DataColumn("IsExchangeRate", typeof(bool)), 
            new DataColumn("Details", typeof(string)), 
            new DataColumn("Marked", typeof(bool)), 
            new DataColumn("Ignore", typeof(bool)) });
        dt.Rows.Add(1, "111", "01/02/2018", "BN", "123455AAA", "CM", 124, "GA", 100, 5, true, "Details", true, true);
        dt.Rows.Add(2, "222", "02/02/2018", "BN1", "123455AAA112", "CM1", 12411, "GA1", 200, 6, true, "Details", true, false);
        gvtfaTrust.DataSource = dt;
        gvtfaTrust.DataBind();
    }
}
protected void Ignore_Click(object sender, EventArgs e)
{
}
[WebMethod()]
public static string Mark(int id, string Marked, string LabelFullname)
{
    try
    {
        int age = int.Parse("1");
        return "success";
    }
    catch (Exception ex)
    {
        return "failed";
    }
}

protected void gvtfaTrust_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[11].Controls.OfType<CheckBox>().FirstOrDefault().Checked)
        {
            e.Row.Cells[7].Controls.OfType<DropDownList>().FirstOrDefault().Enabled = false;
            e.Row.Cells[7].Controls.OfType<DropDownList>().FirstOrDefault().Visible = true;
            e.Row.Cells[7].Controls.OfType<Label>().FirstOrDefault().Visible = true;
            e.Row.Cells[9].Controls.OfType<TextBox>().FirstOrDefault().Enabled = false;
            e.Row.Cells[12].Controls.OfType<CheckBox>().FirstOrDefault().Enabled = false;
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn() {
                            New DataColumn("ID", GetType(Integer)),
                            New DataColumn("BankAccount", GetType(String)),
                            New DataColumn("DateDeposited", GetType(String)),
                            New DataColumn("PayName", GetType(String)),
                            New DataColumn("Reference", GetType(String)),
                            New DataColumn("Memo", GetType(String)),
                            New DataColumn("EntryType", GetType(Integer)),
                            New DataColumn("GLAcct", GetType(String)),
                            New DataColumn("Amount", GetType(Integer)),
                            New DataColumn("ExchangeRate", GetType(Integer)),
                            New DataColumn("IsExchangeRate", GetType(Boolean)),
                            New DataColumn("Details", GetType(String)),
                            New DataColumn("Marked", GetType(Boolean)),
                            New DataColumn("Ignore", GetType(Boolean))})
        dt.Rows.Add(1, "111", "01/02/2018", "BN", "123455AAA", "CM", 124, "GA", 100, 5, True, "Details", True, True)
        dt.Rows.Add(2, "222", "02/02/2018", "BN1", "123455AAA112", "CM1", 12411, "GA1", 200, 6, True, "Details", True, False)
        gvtfaTrust.DataSource = dt
        gvtfaTrust.DataBind()
    End If
End Sub
Protected Sub Ignore_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub
<WebMethod()>
Public Shared Function Mark(ByVal id As Integer, ByVal Marked As String, ByVal LabelFullname As String) As String
    Try
        Dim age As Integer = Integer.Parse("1")
        Return "success"
    Catch ex As Exception
        Return "failed"
    End Try
End Function
Protected Sub gvtfaTrust_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvtfaTrust.RowDataBound
    If e.Row.RowType = DataControlRowType.DataRow Then
        If e.Row.Cells(11).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked Then
            e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Enabled = False
            e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Visible = True
            e.Row.Cells(7).Controls.OfType(Of Label)().FirstOrDefault().Visible = True
            e.Row.Cells(9).Controls.OfType(Of TextBox)().FirstOrDefault().Enabled = False
            e.Row.Cells(12).Controls.OfType(Of CheckBox)().FirstOrDefault().Enabled = False
        End If
    End If
End Sub

Screenshot