Trouble accessing selected value from drop down list in ASP.NET codebehind following modification of Javascript attribute

Does anyone know why ASP.NET code behind cannot retrieve the selected value?

After investigating, I discovered that the issue lies within the JavaScript function;

Specifically in the set attribute section:

process.options[process.selectedIndex].setAttribute("style", "color:red;font-weight:600;");
process.options[process.selectedIndex].setAttribute("disabled", "disabled");

If I remove these setAttribute lines, ASP.NET code behind can successfully obtain the selected value.

Are there any solutions available if I still want to utilize the setAttribute component?

Example:

HTML

    <html>
    <table style="margin-left: auto; text-align: center; margin-right: auto; font-size: large; width: 50%" border="1">
                <tr>
                    <td class="auto-style1">Process Name</td>
                    <td class="auto-style2">:</td>
                    <td class="auto-style3">
                        <asp:DropDownList ID="ddl_processname" runat="server" CssClass="ddl-style" onchange="focustester()">
<asp:ListItem Value="P1">Process 1</asp:ListItem>
                        <asp:ListItem Value="P2">Process 2</asp:ListItem>
                        <asp:ListItem Value="P3">Process 3</asp:ListItem></asp:DropDownList>
                        <br />
                        <br />
                        <asp:Label ID="lbl_statio" runat="server" Text=""></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1">Tester Name</td>
                    <td class="auto-style2">:</td>
                    <td class="auto-style3">
                        <asp:TextBox ID="txt_testername" runat="server" AutoPostBack="true" OnTextChanged="TextBox_TextChanged" CssClass="txt-style"></asp:TextBox>
                    </td>
                </tr>
            </table>
        </div>
        <script>
            function focustester() {
                var process = document.getElementById('<%= ddl_processname.ClientID%>');
    
                if (process.value != "") {
                    process.options[process.selectedIndex].setAttribute("style", "color:red;font-weight:600;");
                    process.options[process.selectedIndex].setAttribute("disabled", "disabled");
    
    
                    document.getElementById('<%= txt_testername.ClientID%>').focus();
                }
            }
        </script>
        </html>

ASP.NET Code Behind

protected void TextBox_TextChanged(object sender, EventArgs e)
        {
            TextBox txt_ID = (TextBox)sender;
            string get_certain_box = "";
            
            // rest of the code omitted for brevity
        }

Answer №1

To ensure data security, incorporate a hidden field and use JavaScript to assign the dropdown value to this field. Then, on the server side, access the hidden value to retrieve the dropdown selection.

<asp:HiddenField ID="hdnProcess" runat="server" />

JavaScript Function:

function focustester() {
    var process = document.getElementById('<%= ddl_processname.ClientID%>');
    
    if (process.value != "") {
        process.options[process.selectedIndex].setAttribute("style", "color:red;font-weight:600;");
        process.options[process.selectedIndex].setAttribute("disabled", "disabled");
        
        var hdn = document.getElementById('<%=hdnProcess.ClientID%>');
        hdn.value = process.value;

        document.getElementById('<%= txt_testername.ClientID%>').focus();
    }
}

Server-Side Handling:

protected void txt_testername_TextChanged(object sender, EventArgs e)
{
    TextBox txt_ID = (TextBox)sender;
    string get_certain_box = "";
    string ddlval = hdnProcess.Value.ToString();

    if (ddlval == "")
    {
        Response.Write(@"<script language=javascript>alert('Please select Process first...')</script>");
        txt_ID.Text = "";
        ddl_processname.Focus();
    }
    else
    {
        if (txt_ID.Text.ToString() == "")
        {
            get_certain_box = (txt_ID.ID.ToString() == "txt_testername") ? "Tester field" : "txtID";
            Response.Write(@"<script language=javascript>alert('" + get_certain_box + " cannot be blank...')</script>");
            txt_ID.Focus();
        }
        else
        {
            if (txt_ID.ID.ToString() == "txt_testername")
            {
                Response.Write(@"<script language=javascript>alert('Success')</script>");
            }
        }
    }
}

Answer №2

It's possible that my memory is incorrect, but I recall that the code behind may not be able to retrieve data if the dropdown is disabled or in some other state. Would it be feasible for you to disable the dropdown after it moves to focustester()? Alternatively, if you are adamant about using JavaScript, why not consider a workaround such as inserting the value into a hidden field when utilizing setAttribute?

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

Acquire the jQuery cookie with the power of AngularJS

I am currently utilizing jquery.cookie v1.4.1 to set a cookie in the following manner: $.cookie('userCookie', $("#user").val()); The value returned by $("#user").val() is typically something like 'username' Now, within an angular app ...

Refreshing and paginating data tables

I'm currently working on a basic CRUD data table and I have added a refresh function using AJAX to dynamically append HTML without reloading the page. Everything was working fine until I introduced pagination from Laravel. The issue now is that only t ...

The addEventListener feature in Bootstrap 5.2.3 seems to be malfunctioning

I have a sample page with a Bootstrap dialog being returned from the server. I want to display it inside a DIV. However, when clicked, I receive this error: Uncaught TypeError: myModal.addEventListener is not a function It points to this line of code: ...

Creating a custom date selection component in Angular 2 RC1

Can anyone recommend a datepicker that is compatible with Angular 2 RC1? I noticed that ng2-datepicker seems to be using angular2 RC1, but when trying to install it, it's asking for Angular 2 Beta. Would appreciate any assistance. Thank you in advan ...

Using Vue's computed property setter with an object as a prop

I have a new concept for an input component where different objects can be passed, displayed as CSV, and allow for text editing/validation with style changes based on validation results. Check out the code snippet I've been working on: <div id=&quo ...

Tips for creating a fixed AppBar and table headers that are stacked underneath each other on a single page while scrolling, using Material UI

Check out these screenshots of the AppBar and Table: View screenshot at the top of the page. Screenshot when scrolling down Take a look at the code for the AppBar and Table: <AppBar position="static" style = {{background : "#00009A"}}> ...

Include the component with the function getStaticProps loaded

I am currently working on a project using NextJs and I have created a component to load dynamic data. The component works fine when accessed via localhost:3000/faq, but I encounter an error when trying to import the same component into index.js. It seems l ...

Send key-value pairs to the function using ng-model

I am currently working on a functionality that involves extracting an object from json and displaying its key-value pairs using 'ng-repeat' in AngularJS. The form includes checkboxes where the value can be either true or false, determining if the ...

The functionality of Dnd-kit nested is functioning properly, however, one specific component is unfortunately

Currently, I am dealing with a two-dimensional array that results in two nested dnd-kit drag and drop fields. The nested dnd functions correctly; however, the first one sorts items when moved without any animations (even when moving my div). Below is the ...

What is the most efficient way to calculate the total sum of all product amounts without using Jquery?

I am working with a dynamic table where data is inserted and the total of each product is calculated by multiplying the price by the quantity. What I need now is to get the sum of all the totals for each product. You can see how the table looks here: htt ...

Having trouble with your YouTube Live Stream not playing in the React Player version 2.9.0?

I successfully integrated react-player into my react.js website and it was working perfectly. However, after a few days, it suddenly stopped functioning. Even updating the plugin to version 2.9.0 did not resolve the issue. Strangely enough, standard YouTub ...

While attempting to utilize inner class functions in Node JS, an error is being encountered

I've been delving into Node JS and exploring how to implement an OOP structure within node. I've created a simple class where I'm using functions to verify and create users in a database. However, I'm encountering a TypeError when attem ...

"What is the best way to retrieve the id of the element that triggered a JavaScript onclick

I'm facing an issue with my GridView where I have information displayed in each row. When a user clicks on a row, more related information is supposed to be shown in a separate DIV. However, I am unable to target the specific row when trying to change ...

Creating a custom data type with a specific value in GraphQL

I am new to graphQL and have some questions regarding it. After going through the documentation, I decided to build something of my own. Currently, my setup is quite simple. At the beginning of my application, I have the following code: const express = ...

JSONP OpenWeather API

I've been trying to access and retrieve weather data from OpenWeather using their API, but unfortunately, I'm facing some difficulties in getting it to work. It seems like there might be an issue with the way I am fetching the JSON data. To quer ...

Addon for Firefox: Image Upload

I am looking for a way to streamline the process of uploading an image to a website through a Firefox Addon. While I know it is possible to use createElement('canvas'), convert Image data to base64, and XHR POST the data, I would prefer to lever ...

What could be causing my button to not capture the value of this input text field?

After clicking the button, I am trying to log the value of the input text field in the console. However, it just shows up as blank. Despite checking my code multiple times, I can't seem to figure out why. Any insights would be greatly appreciated! &l ...

The Socket.io authorization feature is failing to refresh session information

I am currently working on implementing Socket.IO's authorization function to retrieve session data. However, I have encountered an issue where even after logging out and destroying the session, Socket.IO retains the old session information, which is l ...

Can a text file be loaded into the title of a Bootstrap tooltip?

Looking to dynamically load a text file into bootstrap tooltip titles. Here is a snippet of working code with hardcoded values: <div> <a id="A" type="button" class="btn btn-outline-secondary btn-lg" data-toggle=& ...

The process of incorporating types into Node.js and TypeScript for handling req and res objects

Check out the repository for my project at https://github.com/Shahidkhan0786/kharidLoapp Within the project, the @types folder contains a file named (express.d.ts) where I have added some types in response. The (express.d.ts) file within the @types folde ...