Issue with binding Ajax data in dropdown list was not resolved accurately

Within my gridview, each row has an option to Edit. The desired scenario is that upon clicking the EDIT button, it redirects me to the next tab with the corresponding SAP ID from that particular row populated in a dropdownlist.

However, the current issue I am facing is that on the first click of the edit button, only one value is displayed in the list.

On the second click, two values are shown in the list. This is not the intended behavior; I only want the data value for the specific row that I clicked the edit button on.

Below, you can find my GridView and AJAX code for binding values:

GRIDVIEW

<asp:GridView ID="grdSapDetails" runat="server" PageSize="10" AutoGenerateColumns="false">
                <Columns>
                    <asp:BoundField DataField="SAP_ID" HeaderText="Sap Id" />
                    <asp:BoundField DataField="SITE_NAME" HeaderText="Site Name" />
                    <asp:BoundField DataField="SITE_ADDRESS" HeaderText="Site Address" />
                    <asp:TemplateField HeaderText="Edit">
                        <ItemTemplate>
                            <input type="button" onclick='return HighlightTabFunction(this)' value="Edit" id="btnEdit" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

AJAX

function HighlightTabFunction(a) {
        var row = a.parentNode.parentNode;
        var rowIndex = row.rowIndex - 1;
        var SAPID = row.cells[0].innerHTML;
        $.ajax({
            url: "UBRDashboard.aspx/GETSTATEFROM_SAP",
            dataType: "json",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({ SAPID: SAPID }),
            async: true,
            processData: false,
            cache: false,
            success: function (r) {
                $('a[href="#tabs-2"]').click();
                var ddlSapID = $("[id*=ddlSapID]");
                ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
                $("#hdnState").val(r.d);
            },
            error: function (xhr) {
                alert('Error while selecting list..!!');
            }
        })

Answer №1

If you want to add a new item to the dropdown list, make sure to first remove any existing items. Use the remove() function on the children of the dropdown (select) element.

success: function (r) {
            $('a[href="#tabs-2"]').click();
            var ddlSapID = $("[id*=ddlSapID]");
            ddlSapID.children().remove(); // Remove existing options before adding new one
            ddlSapID.append($("<option></option>").val(r.d).html(row.cells[0].innerHTML));
            $("#hdnState").val(r.d);
        },

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

Local development and the same origin policy: a necessary pairing

While working on my Ember front end calling a Spring/Rest/MongoDB backend running locally for development, I encountered a same origin policy error. I am curious about the common workarounds for this issue. Below is the code snippet I'm using: App = ...

Add new items to an array in mongoose without affecting existing elements within the array

Two different entity structures are in place: Blog Setup: const blogSetup = new mongoose.Schema( { title: { type: String, min: 3, max: 20, required: true }, content: { type: String, required: true }, likes: { type: Number, required: true, de ...

Issue with JQuery image upload functionality not functioning correctly for upcoming events

In order to enable users to upload images with their posts, I have implemented an upload form alongside every reply form. Users can upload an image by clicking the upload button and then submitting the post. Currently, the upload form works for the first ...

A guide on invoking a JavaScript function after receiving a response from an AJAX request

I am facing an issue with a $.POST call that returns the name of a function to be executed, however, the function is not being triggered and I'm unsure why. Below is an example: JavaScript file snippet: $(function(){ $.post('test.php&apos ...

The post request body fails to be recognized, resulting in undefined values being saved to MongoDB

I'm currently facing an issue with my MERN stack app. My express server is functioning well and returns results with Postman. However, I'm encountering difficulties with the post request in the front-end using axios. While I can successfully run ...

Adding a JavaScript file to the header in CakePHP using the view section

The CakePHP documentation states: By default, script tags are inserted into the document in-line. If you wish to change this behavior, you can set $options['inline'] to false. This will cause the script tags to be placed in a script block whic ...

What is the best way to use jQuery to increment the number in an input field by a specific value?

My goal is to utilize jQuery to increment a number in an input field and then display the updated value in the same input field. The specific id of this input field is "total". Here's my attempt so far: function addBag(){ var bagprice = 79.99; ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

Angular 2 Error: Unresolved Promise rejection - Unable to assign value to reference or variable

I'm currently working on an Ionic 2 app that includes a barcode reader feature. However, I encountered the following issue while trying to display data: Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: ; Task: Promi ...

The Justin TV API: Leveraging the Power of Jquery and JSON

Could someone assist me with using the Justin TV API? I have looked through their documentation and found an example along with returned values (Here's the xml file). However, I am having trouble understanding where it specifies which channel to pull ...

Ignore the first checkbox selection and increase the original value by .10 with each subsequent checkbox selection

In my scenario, there is a set of checkboxes that are linked to the pricing system. Specifically, I need the base price to remain unchanged when the first checkbox is ticked. Subsequently, for each additional checkbox selected, an increment of $0.10 shou ...

Tips for verifying if a webpage request originated from a user's inbox

I am currently working on a web application that sends a download link to subscribers. Subscribers can click the link from their inbox to access and download a pdf document. However, I am looking for a way to restrict access to the pdf document only when ...

Any tips on how to effectively integrate dynamic theming in CSS?

I am currently developing a theming feature for my web application, allowing users to select a theme that will dynamically change the color of various elements. Here is an example of the theme selector: <div id="theme-selector"> <div id="theme- ...

Sending SQL data to a Node.js module upon receiving a client request

Currently, I am establishing a connection to a SQL database and retrieving data on the view by using res.json. The client initiates a request - my server employs an MSSQL driver and a connection string to establish a connection with the database and fetch ...

Ensure that newly added elements are aligned with the settings of the slide's

I've encountered an issue with my jQuery slider that affects a div's CSS on slide. Everything works as expected, except when I add a new div, the settings from the slider aren't applied to the new div until the slider is moved again. HTML ...

Tips for integrating SQL queries into a document that consists mostly of JavaScript and JQuery

I am currently in the process of integrating a SQL database write into my file that is primarily comprised of JavaScript and jQuery. While I have come across some PHP resources online, I am facing challenges incorporating the PHP code into my existing scri ...

Javascript is failing to execute promises in sequence

Currently, I am facing an issue with the execution of the code below using promises. The problem lies in the fact that the promise is not executing sequentially; it does not wait for the first block to finish before moving on to the next block. Here is th ...

Track your status with jQuery technology

I have a link: <a href="/test/number/3/phone/0">33df</a> Is there a way to determine if the words 'number' and 'phone' are present in this link? I am looking for a function similar to: check('number', ' ...

Discover the index of the row when the value in the dropdown list is updated

I'm faced with a challenge regarding an HTML Table that contains a dropdown list in every row. I would like the background of each row to change whenever the value in the dropdown list is modified. Below is the code snippet: <table id="table1"> ...

Using jQuery for file upload validation in Asp.net

I've implemented a jQuery function to perform client-side validation for an ASP.NET file upload control. Here is the code snippet: function setUplaodButtonState() { var maxFileSize = 4096000 // 4MB -> 4000 * 1024 var fileUplaod = $("#<% ...