js獲取select下拉框的value值和text文本值


介紹一種取下拉框值以及綁定下拉框數據的方法    這里用到的jquery-ui-multiselect插件

 

 1、前台html代碼

<span class="ModuleFormFieldLabel" style="float: left; padding-top: 3px;">品類:</span>
   <asp:HiddenField runat="server" ID="hidCarType" />  //隱藏控件,用來存放select value值,傳到后台顯示下拉數據用
   <select id="mulselCarType" name="mulselCarType" multiple="multiple">   //multiple為多選屬性
     <%=this.htmlCarType %>   //后台綁定數據
   </select>

<asp:HiddenField ID="hid_Cartype" runat="server" />   //隱藏控件,用來存放select text文本值,傳到后台顯示文本值
   <asp:Label  ID="x_lb_Cartype" runat="server" Text="品類:" Visible="false"></asp:Label>
   <span style="white-space:normal;">
    <asp:Literal ID="lbCartype" runat="server" ></asp:Literal> //lable用來在頁面顯示文本值
  </span>

 

2、獲取值js代碼

function getValue() {        
            //獲取text值傳入后台
            var objType = $("#mulselCarType").find("option:selected");   //找到控件id,並且找到被選中的option
            var strType = [];   //定義數組
            for (var i = 0; i < objType.length; i++) {
                strType[i] = objType[i].text;   //循環option的長度,取到text值放入數組
            }
            document.getElementById('<%=hid_coust.ClientID %>').value = strType;   //將數組中的值放入隱藏控件(默認每個字符中間使用','隔開,英文',')

            //獲取text值傳入后台
            var objCarType = [];
            $("#mulselCarType").find("option:selected").each(function () {   
                objCarType.push($(this).text());      //找到id,找到選中的option,直接each遍歷,將text值push到數組
            });
            document.getElementById('<%=hid_Cartype.ClientID %>').value = objCarType.join(",");    //將數組的值放入隱藏控件,join(","),字符中間用中文","隔開

        
            //獲取value值傳入后台
            var carType = [];     //multiselect是jquery-ui-multiselect插件,方法詳見官方文檔
            $("#mulselCarType").multiselect('getChecked').each(function () { carType.push($(this).val()); });
            document.getElementById("<%=hidCarType.ClientID %>").value = carType.join(",");
        };

 

3、后台取值賦值代碼

     public string htmlCarType = string.Empty;

      //品類
        private void InitCarType()
        {
            if (!string.IsNullOrEmpty(hidAgent.Value))
            {
                using (SqlDBAccess dbAccess = new SqlDBAccess(AppFunction.ConnectionString))
                {
            //連接數據將數據從表取出,循環放入option,綁定下拉顯示數據 DataTable dt = dbAccess.ExecuteTable("select agent_id,name from tb_agent where brand_id in (" + hidAgent.Value + ") and status='ready'"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (DataRow dr in dt.Rows) { sb.AppendLine(string.Format("
<option value='{0}'>{1}</option>", dr["agent_id"].ToString(), dr["name"].ToString())); } this.htmlCarType = sb.ToString(); } } }

      //品類
      if (hid_Cartype.Value == "")     //將文本值放入lable控件顯示
        x_lb_Cartype.Visible = false;
      else
        x_lb_Cartype.Visible = true;
        lbCartype.Text = hid_Cartype.Value;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM