Showing posts with label Dropdown. Show all posts
Showing posts with label Dropdown. Show all posts

Saturday, September 23, 2017

jQuery Chosen Plugin in SharePoint

jQuery Chosen Plugin in SharePoint

Step1: Create a custom list.
Step2: Create a choice column and select check boxes allow multiple selection.
Step3: Create NewForm1.aspx using Designer and make it default form.

Setp4: Edit and add below code and save NewForm1.aspx
Code:
Replace below code in NewForm1.aspx
Old code:
--------------------
<tr>
        <td width="190px" valign="top" class="ms-formlabel">
            <h3 class="ms-standardheader">
                <nobr>Choice</nobr>
            </h3>
        </td>
        <td width="400px" valign="top" class="ms-formbody">
            <SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="Choice" __designer:bind="{ddwrt:DataBind('i',concat('ff2',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Choice')}" />
            <SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="Choice" ControlMode="New" />
        </td>
    </tr>
Updated code:
--------------------
<tr>
            <td width="190px" valign="top" class="ms-formlabel">
                <h3 class="ms-standardheader">
                    <nobr>Choice</nobr>
                </h3>
            </td>
            <td width="400px" valign="top" class="ms-formbody">
                <table>
                    <tr>
                        <td>
                            <div id="divChoice"></div>
                        </td>
                    </tr>
                    <tr>
                        <td id="tdChoice">
                            <SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="Choice" __designer:bind="{ddwrt:DataBind('i',concat('ff2',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Choice')}" />
                            <SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="Choice" ControlMode="New" />
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
Replace below code also.
Old code:
--------------------
<asp:content contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">
    <sharepoint:delegatecontrol runat="server" controlid="FormCustomRedirectControl" allowmultiplecontrols="true" />
    <sharepoint:uiversionedcontent uiversion="4" runat="server">
        <contenttemplate>
            <sharepoint:cssregistration name="forms.css" runat="server" />
        </contenttemplate>
    </sharepoint:uiversionedcontent>
</asp:content>

Updated code:
--------------------
<asp:content contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">
    <sharepoint:delegatecontrol runat="server" controlid="FormCustomRedirectControl" allowmultiplecontrols="true" />
    <sharepoint:uiversionedcontent uiversion="4" runat="server">
        <contenttemplate>
            <sharepoint:cssregistration name="forms.css" runat="server" />
        </contenttemplate>
    </sharepoint:uiversionedcontent>
    <!--<link rel="stylesheet" href="/sites/dev/SiteAssets/Chosen/chosen.min.css"/>
    <script type="text/javascript" src="/sites/dev/SiteAssets/Chosen/jquery.min.js"></script>
    <script type="text/javascript" src="/sites/dev/SiteAssets/Chosen/chosen.jquery.min.js"></script>
    <script type="text/javascript" src="/sites/dev/SiteAssets/Chosen/chosen.proto.min.js"></script>-->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.proto.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            buildChosen();
            $("#selectChoice").chosen().change(function () {
                var selectedItemsChoice = $(this).val();
                $("#tdChoice td").each(function (index) {
                    $(this).find(':checkbox').prop('checked', false);
                    for (var i = 0, len = selectedItemsChoice.length; i < len; i++) {
                        if ($(this).text().trim() == selectedItemsChoice[i].trim()) {
                            $(this).find(':checkbox').prop('checked', true);
                        }
                    }
                });
            });
            $("#tdChoice").hide();
        });
        function buildChosen() {
            htmlChoice = '<select  class="Choice" multiple="multiple" id="selectChoice">';
            $("#tdChoice td").each(function (index) {
                if ($(this).find(':checkbox').prop('checked')) {
                    htmlChoice += "<option value='" + $(this).text() + "' selected='selected'>" + $(this).text() + "</option>";
                } else {
                    htmlChoice += "<option value='" + $(this).text() + "'>" + $(this).text() + "</option>";
                }
            });
            $('#divChoice').html(htmlChoice);
            $('#selectChoice').chosen({ width: "400px" });
        }
    </script>
</asp:content>
Step5: 
Test the application. Click on Create new item from ribbon in list.
before update code:
--------------------

After update code:
--------------------

Tuesday, October 8, 2013

jQuery Cascading Dropdown List in Asp.net with Example

WebForm4.aspx:-
---------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="WebApplication2.WebForm4" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#<%=ddlstate.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlstate.ClientID %>').append('<option selected="selected" value="0">Select State</option>');
            $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
            $('#<%=ddlcountries.ClientID %>').change(function () {
                var country = $('#<%=ddlcountries.ClientID%>').val()
                $('#<%=ddlstate.ClientID %>').removeAttr("disabled");
                $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
                $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/BindStates",
                    data: "{'country':'" + country + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlstate.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong ' + data)
                    }
                });
            });
            $('#<%=ddlstate.ClientID %>').change(function () {
                var stateid = $('#<%=ddlstate.ClientID%>').val()
                $('#<%=ddlcity.ClientID %>').removeAttr("disabled");
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/BindRegion",
                    data: "{'state':'" + stateid + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlcity.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong')
                    }
                });
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Country</td>
                    <td>
                        <asp:DropDownList ID="ddlcountries" runat="server"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>State</td>
                    <td>
                        <asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>Region</td>
                    <td>
                        <asp:DropDownList ID="ddlcity" runat="server"></asp:DropDownList>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
WebForm4.aspx.cs:-
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Services;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCountries();
            }
        }

        private void BindCountries()
        {
            DataTable dtName = new DataTable();

            //Add Columns to Table
            dtName.Columns.Add(new DataColumn("CountryName"));
            dtName.Columns.Add(new DataColumn("CountryID"));

            //Now Add Values
            dtName.Rows.Add("Countries1", "0");
            dtName.Rows.Add("Countries2", "1");
            dtName.Rows.Add("Countries3", "2");

            //At Last Bind datatable to dropdown.
            ddlcountries.DataSource = dtName;
            ddlcountries.DataTextField = dtName.Columns["CountryName"].ToString();
            ddlcountries.DataValueField = dtName.Columns["CountryID"].ToString();
            ddlcountries.DataBind();
        }

        [WebMethod]
        public static string BindStates(string country)
        {
            StringWriter builder = new StringWriter();

            DataTable dtStates = new DataTable();

            //Add Columns to Table
            dtStates.Columns.Add(new DataColumn("StateName"));
            dtStates.Columns.Add(new DataColumn("StateID"));

            //Now Add Values
            dtStates.Rows.Add("State1", "0");
            dtStates.Rows.Add("State2", "1");
            dtStates.Rows.Add("State3", "2");

            builder.WriteLine("[");
            if (dtStates.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select State\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dtStates.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dtStates.Rows[i]["StateName"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dtStates.Rows[i]["StateID"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select State\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }

        [WebMethod]
        public static string BindRegion(string state)
        {
            StringWriter builder = new StringWriter();

            DataTable dtRegion = new DataTable();

            //Add Columns to Table
            dtRegion.Columns.Add(new DataColumn("RegionName"));
            dtRegion.Columns.Add(new DataColumn("RegionID"));

            //Now Add Values
            dtRegion.Rows.Add("Region1", "0");
            dtRegion.Rows.Add("Region2", "1");
            dtRegion.Rows.Add("Region3", "2");

            builder.WriteLine("[");
            if (dtRegion.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dtRegion.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dtRegion.Rows[i]["RegionName"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dtRegion.Rows[i]["RegionID"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }
    }
}
Source:-
Thank You.

Featured Post

Building Secure APIs with FastAPI and Azure AD Authentication

Building Secure APIs with FastAPI and Azure AD Authentication Published on September 2, 2025 In today's world of microservices and API-f...

Popular posts