简体   繁体   中英

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 get 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.

在纯JavaScript中:

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

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();

With jquery:

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

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