2012-01-17 89 views
0

你好,我试图使用autocomplete dropdownlist插件,名称是ufd。 无论如何,我有dropdownlist,我想要在代码隐藏click_event上得到这个选定的值(或文本)。 如果我可以从下拉列表中删除所有选定的ATTR,并添加选择的ATTR到所选的选项,这将work.But这removeAttr不工作:(请帮我jquery removeAttr无法正常工作

 $(function() { 
     var element = $("#DropDownList1"); 
     $(element).change(function() { 
     $(element).find('option').removeAttr('selected'); //this is not working 
     $(element + "option[value=" + $(element).val() + "]").attr("selected", "selected"); 
     }); 
     }); 

    <asp:DropDownList ID="DropDownList1" runat="server"> 
    </asp:DropDownList> 
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> 

代码隐藏:

protected void Page_Load(object sender, EventArgs e) 
    { 
     using (TalepService tService = new TalepService()) 
     { 
      DropDownList1.DataSource = tService.ddlTalepDurumDoldur(); 
      DropDownList1.DataTextField = "talepDurumu"; 
      DropDownList1.DataValueField = "talepDurumID"; 
      DropDownList1.DataBind(); 
     } 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     string text = DropDownList1.SelectedItem.Text; 
     string value = DropDownList1.SelectedValue; 
    } 
+2

你为什么要这么做?它看起来像发生“变化”时,您手动执行浏览器自动执行的操作。我的意思是如果发生“变化”事件,那么选定的选项将会被更改。 – 2012-01-17 21:19:14

+0

我回答了贾斯珀我在想什么。我不知道为什么,但当我选择任何选项(更改),看不到这是在萤火虫上选择。这就是为什么我想手动去获得代码隐藏的这个值。问题仍在继续:) – blackraist 2012-01-17 21:54:30

+0

你是什么意思,你看不到它被选为萤火虫?如果你想要这个值,只需要执行'$(this).val()',但是不应该有任何理由去操作属性。 – 2012-01-17 21:58:13

回答

1

您是从jQuery的对象,其是具有在这条线的问题创建的jQuery对象(我假设):

$(element + "option[value=" + $(element).val() + "]").attr("selected", "selected"); 

因为element是一个jQuery对象(关键字,对象),并要添加该对象的字符串。

试试这个:

$(function() { 
    var element = $("#DropDownList1"); 
    element.change(function() { 
     var theVal = element.val();//get the current value since it will be removed on the next line 
     element.find('option').removeAttr('selected'); //this is not working 
     element.find("option[value=" + theVal + "]").attr("selected", "selected"); 
    }); 
}); 

这里是一个演示:http://jsfiddle.net/LjhwW/1/

在创建这个演示中,我意识到同样的事情,“我不是我是”(在评论)。为什么您手动更改change事件的选定元素,浏览器无论如何都会这样做。

0

改变与jQuery的一个选择的选择值的正确方法是通过设置它的价值。

$("#DropDownList1").val("new-selected-value") 
0

设置的selectedIndex财产为-1以清除选定的项目。

1

element已经是一个jQuery对象,所以你不必在其上使用$()。如果它是一个jQuery对象,我们通常会在$前添加变量名称。尝试这个。

$(function() { 
    var $element = $("#DropDownList1"); 
    $element.change(function() { 
     var val = this.value; 
     $element.find('option').removeAttr('selected') 
     .filter("[value=" + val + "]") 
     .attr("selected", "selected"); 
    }); 
}); 
+0

我发布了几乎相同的代码,并且意识到在change事件处理程序的最后一行获取'$ element.val()'将不会返回任何内容,因为它之前的行将删除'selected'属性。你也在'change'事件处理程序的第一行之后有一个分号,它将停止执行。 – Jasper 2012-01-17 21:26:49

+0

@Jasper - 感谢分号,完全错过了它。 – ShankarSangoli 2012-01-17 21:30:48

+0

嘿嘿,我试着用'this.value'完成相同的工作,修正是在清除之前缓存select的值:http://jsfiddle.net/LjhwW/2/(这是你的代码的演示) – Jasper 2012-01-17 21:32:52