获取文本选择Runat =“Server”

时间:2011-03-14 11:55:33

标签: javascript jquery select jquery-selectors selection

   <select   id="Select1">
         <option>1</option>
         <option>2</option>
         <option>3</option>
  </select>

alert($("#Select1").val());

此代码是正确的并且返回当前值。

BUT

   <select runat="server"   id="Select1">
         <option></option>
  </select>

function parseXmlQuestion(xml)
{

   $(xml).find("Question").each(function()
  { 
     var value=$(this).find('Text').text()
     $('#<%=Select1.ClientID %>').
      append($("<option></option>").
      attr("value",value).
      text(value)); 
   });

}

alert( $('#<%=Select1.ClientID %>').val());
alert( $('#<%=Select1.ClientID %> option:selected').val());

alert( $('#<%=Select1.ClientID %>').text());
alert( $('#<%=Select1.ClientID %> option:selected').val());

alert( $('#<%=Select1.ClientID %>').html());
alert( $('#<%=Select1.ClientID %> option:selected').val());

返回null或undefined。

2 个答案:

答案 0 :(得分:0)

您需要从

中删除<option></option>
   <select runat="server"   id="Select1">
         <option></option> <-- your values get added after this so probably the null is coming from here
  </select>

它应该像

   <select runat="server"   id="Select1"></select>

答案 1 :(得分:0)

好的,你有点奇怪,每次回答你都会帮助我们......

这是你应该做的。

  1. 测试这会返回正确的ID。 <%=Select1.ClientID %>应为Select1
  2. 检查你的xml,也就是说,正确,(使用json,这更容易),包括你的xml标签的大写。如果你还没有进化,那么console.log(value)alert(value)也是如此:)
  3. 应该在页面的某处调用
  4. parseXmlQuestion(),否则你只是坐着的鸭子没有被射击或者没有告诉它用其他的话来运行