0

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?

1

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

to make sue that the Dom is loaded i can use jquery $(document).ready() right? and i have to use your code inside my usercontrol where the select is located? will this also work if the select was inside a div?
Oh, you are using jquery? You should have stated this in your question. Yes you should use $(document).ready but with jquery you could also use CSS selectors. For example give your DropDownList a CSS class and then: var selectedValue = $('.myddl').val();. You don't need to bother with mangled ids.
As an addition to DOM load if you put your script at the end of the page just before the closing body you no longer need to wrap your code in a $(document).ready statement because at that moment it will already be loaded.
0

In plain JavaScript:

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

Comments

0

With jquery:

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.