Obtain the value of the selected item from a dropdown list that has been dynamically populated

Hello, I have successfully populated a list of items into an asp:DropDownList using JavaScript. Here is the code snippet:

 if (document.getElementById("<%=gdview.ClientID %>")!=null)
    {
    var rows = document.getElementById("<%=gdview.ClientID %>").getElementsByTagName('tr');
    var cells = rows[1].getElementsByTagName('td');
  //alert(cells)
    i = 2;
    while (i < cells.length)
    {
        document.getElementById("<%=ddl_noofCols.ClientID %>").options[i] = new Option(i + 1, i);
        i++;
           }
    document.getElementById("<%=ddl_noofCols.ClientID %>").options[2].selected =true;
    alert(document.getElementById("<%=ddl_noofCols.ClientID %>").options[2].text);
    }

In this script, the gridview is represented by gdview, and its number of columns are added to the dropdownlist. By default, the third option (index 2) is selected. However, when trying to retrieve the selected item or value using ddl_noofCols.SelectedValue, it returns null.

Could someone advise on how to properly obtain the selected value?

Thank you for your help!

Answer №1

If you are looking for a similar solution, consider the following code snippet:

let table = document.getElementById("<%=gdview.ClientID %>");
let select = document.getElementById("<%=ddl_noofCols.ClientID %>");
let cells;

if (table) {
    cells = table.rows[1].cells;

    for (let i=2, iLen=cells.length; i<iLen; i++) {
        select.options[i] = new Option(i + 1, i);
    }
    select.options[2].selected = true;
    alert(select.options[2].text);

    // To access the current value of the select element,
    // you can use the value property:
    alert(select.value);
}

The value of the currently selected option can be accessed using select.value. In case the selected option does not have a value attribute or property, the value of the text property is returned, except for IE 8 and below where you may need to do something like this:

let value = select.value;

if (!value) {
    value = select.options[select.selectedIndex].text;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing d3 to parse and track variables within JSON data

To calculate the number of occurrences of s1, s2, and s0 in JSON data and use this information to plot a multiline chart with date (path of date is as follows reviews_details>>variable vf of JSON) on the X-axis versus the number of reviews (s1/s0/s2 ...

Struggling to Deploy Application with ASP.NET Core 1.1

I'm having issues running a dotnet publish command on my Linux server to compile my web application. The error message indicates that my project.json file is missing. Before providing a solution, there have been recent changes that need to be taken i ...

Implementing the Tab key functionality without redirecting to the address bar

I recently integrated a Tab control into my project, but I'm encountering an issue where pressing the Tab key causes the address bar to jump when I try to press another key. This only happens after the Tab key functions correctly in the scene. How can ...

Change the height of a div after submitting a form using Django (Python)

I have a registration form with one submit button. Upon clicking submit, if there is an error, the height of the div increases by setting it to height:auto. However, when I click submit, it changes the height of the div (.continer). Strangely, after one ...

Performing Vue CLI Global Upgrade

Struggling to create a new Vue.js project using the Vue CLI service, I encountered an error. With @vue/cli-service 3.0.0-beta.7 installed (confirmed by running vue -V), attempting to start a new project triggered the following error: ...

Disable the password box

Is there a way to make the password field disabled? @Html.Editor("password") Perhaps something similar to this: Html.TextBoxFor(model => model.User, new {disabled = "disabled"}) ...

Issue with Typescript and rxjs 6: Property is not found on type 'object'

Currently, I am working on a small application using Ionic 3 to query a Firebase database for two sets of data. Initially, I encountered an error during the first build stating "Property does not exist on type '{}'", however, after saving the .ts ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

"Incorporate an image into the data of an AJAX POST request for a web service invocation

I have been attempting (with no success thus far) to include an image file in my JSON data when making a call to a method in my webservice. I have come across some threads discussing sending just an image, but not integrating an image within a JSON data o ...

Using a for loop in JAVASCRIPT to interact with MONGODB

I am running a MongoDB query to fetch data from the database, and the returned information looks like this: { _id: new ObjectId("623rf3f22275f399f88bb"), first_name: 'Are', last_name: 'You', email: '<a href="/c ...

Exploring Techniques for Adjusting Website to User's Screen Resolution

My website is currently designed for a screen resolution of 1024x768. However, I am aware that when viewed on computers with smaller or larger screen resolutions, the layout starts to distort. Is there a way to make the website adaptable to any user&apos ...

What could be the reason for my form submission redirecting to the PHP page?

(I recently discovered that I could edit and reopen the post I had previously made. Feeling a bit confused about the process...) After submitting the form, the email is sent successfully, but then I am redirected to my php page displaying the number 0. Th ...

Evaluating the DateTime between the client browser and the remote server using C#

Let's consider a scenario: I'm working on an ASP.NET MVC website with a form that allows clients to input an expiry date (using JQuery datepicker). After the form submission, I need to validate on the server if the entered date is past the curre ...

The content of a Puppeteer page mysteriously disappears when transferred to another function

My current project involves using Puppeteer for web scraping on my website. I encountered a strange issue where the await page.content() works fine when I console log the content, but turns out to be null when passed as an argument to another JavaScript ...

Having difficulties injecting a Service into a TypeScript Controller

I recently started working with TypeScript and I created a controller where I need to inject a service in order to use its methods. However, I am facing an issue where I am unable to access the service functions and encountering an error. Error TypeError ...

The on() method in jQuery is failing to work on an element that has a class added dynamically

After adding an active class to a link once a product is added to cart, I tried using that class to determine the function of the link. However, the on() click event on the link does not trigger unless the page is reloaded. Below is the code snippet where ...

Display validation messages when the user either clicks out of the textbox or finishes typing

Here are some validation messages: <form name="dnaform" novalidate> <div style="padding-bottom:5px" ng-show="dnaform.uEmail.$pristine || dnaform.uEmail.$valid">Active directory account </div> <div style="padding-bottom:5px;" n ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

Retrieving data based on specified criteria in SQL

I want to create a Stored Procedure that executes based on certain conditions: I have linked 2 Tables together to retrieve necessary data: (I'm passing @LocationID as a parameter) Table 1 "Devices" DeviceID Device Serial Model Carrier LocationID ...

What causes the browser to be blocked when using $.getJSON()?

Managing a page that lists hardware devices monitored for customers can be challenging, especially when considering the status of each device. To avoid slow page load times, I have implemented a strategy where the device list is displayed first, and then t ...