简体   繁体   中英

How to change a dropdownlist item in jQuery?

I have a drop down list for asp.net. I need to change the text of one item. The list is loaded with a table in a database. Because of a weird weird accessibility situation, the only way I can get this task done is through js.

Here is a sample drop down:

<asp:DropDownList ID="myDrop" runat="server" onselectedindexchanged="myDrop_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>

Here are the in-HTML items:

<option value="1">text1</option>
<option value="2">text2</option>
<option value="3">text3</option>

and so on. Thanks!

you can use jquery to change the text of option using jquery filters to change 1st option text you can use ':eq(0)' and for second ':eq(1)' and so on

$("#myDrop>option:eq(0)").text('myName'); 

if you are not sure with the indexing of option the following approach can be used

var Arr = $('#myDrop>option');
$.each(Arr,function(i,data){
if($(data).attr('value') == "2"){
$(data).text("changetext")
}
})

Not sure if this is what you meant. Hope it helps.

https://jsfiddle.net/5oed5wrh/

var ddl = document.getElementById('myDrop');
var index = 1;
ddl.options[index].innerText = "Something new";

I dont know which option you are trying to change so I just picked the middle one. If you are trying to change all of them, you can do so with a simple loop.

Also, if you are using jQuery you can use .text() instead of innerText. I believe innerText is a IE construct. It will help if you have cross-browser compatibility concerns.

var ddl = document.getElementById('myDrop');
var index = 1;
$(ddl.options[index]).text("Something new");

As you've specifically asked for a solution using jQuery:

$('#myDrop option[value="2"]').text("new text")

Select the option that you want to edit and then amend the text inside it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM