开发者

getting an element in JavaScript

i have the following html code:

<select name="drop1" id="Select1" size="4" multiple="multiple">
    <option value="1">item 1</option>
    <option value="2">item 2</option>
    <option value="3">item 3</option>
    <option value="4">item 4</option>
    <option value="0">All</option>
</select>

this code is available in a user control, so its id changes when i run the web application. how can i ge开发者_C百科t the selected items from JavaScript on a button click?


If you are using ASP.NET 4 you could set static ids in web.config:

<system.web>
    <pages clientIDMode="Static"></pages>
</system.web>

this way you know the generated ID.

If you are not using ASP.NET 4.0 an alternative is to declare a global js variable:

<script type="text/javascript">
    // TODO: be careful here and make sure the DOM is loaded
    var mySelect = document.getElementById('<%= Select1.ClientID %>');
</script>

which could be used later to manipulate the select.


In plain JavaScript:

var value = document.getElementById('Select1').value;


With jquery:

$("select[name= drop1]").val()


If you can't use .NET 4.0 to control IDs and you don't want to add extra markup to the page, you need to retrieve the control's element using the Client ID:

var ddl = document.getElementByID('<%= Select1.ClientID %>');

Edit: If you are using jquery, you can do this if you don't want to add an extra class to your DropDownList:

var value = $('#<%= Select1.ClientID %>').val();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜