Trigger JavaScript function from hyperlink in ASP.NET GridView

After experimenting with my dropdownlist, I discovered that if I set visible= 'false', the hyperlink function of the gridview stops working. My dropdownlist has three options, and each time it changes, it needs to redirect the hyperlink to different destinations:

  1. PASTA
  2. Source
  3. Brand

I can only receive the result when clicking the gridview hyperlink if I keep the textbox visible set to 'true'.

<asp:DropDownList ID="stock" runat="server" AutoPostBack="true" AppendDataBoundItems="true"  Width="15%"/>
 <asp:TextBox ID="lblstock" runat="server" Visible="false" />

The gridview hyperlink below only works if the dropdownlist doesn't change:

<asp:HyperLink runat="server" Text='<%# Eval("FOOD_NO")%>' NavigateUrl='<%# String.Format("javascript:openWindow(""../FOOD/FOOD_STG.aspx?FOOD_NO={0}"")", Eval("FOOD_NO"))%>' />
<asp:Label ID="FOOD_NO" runat="server" Visible="False" Text='<%# Bind("FOOD_NO") %>' />

JavaScript:

function openWindow() {

        var result = document.getElementById("lblstock").value.strURL;
        var url = "";
        if (result != "")
        {
            switch (result) {
                case "PASTA":
                    url = "../FOOD_Rep/FOOD_Rep.aspx?FOOD_NO={0}";
                 break;

                case "Source":
                    url = "../FOOD_Ing/FOOD_Ing.aspx?FOOD_NO={0}";
            break;

            case "Brand":
                url = "../FOOD_Brd/FOOD_Brd.aspx?FOOD_NO={0}";
            break;

        }
        var winopen = window.open(url + "&FOOD_ID=" + $("#GROUP_ID").val(), 'Memo', ' left=50, screenx= 10, width=1360,height=820,scrollbars=1,resizable=1,toolbar=0');
        winopen.focus();

    }

Vb code behind:

lblstock.Text = stock.SelectedValue

I have been facing this issue for some time now, any help would be greatly appreciated. Thank you.

Answer №1

Although I haven't had the chance to physically test this yet, it seems like a feasible solution: Clicking on the hyperlink will extract the currently selected value from the DropDownList and utilize it to generate the URL.

This method assumes that the Dropdownlist offers options such as "PASTA", "Source", and "Brand," which are specified in the original javascript function you provided.

The use of jQuery here is for cleaner syntax when creating event handlers. However, if preferred, you could easily convert it to native JavaScript.

DropDownList:

<asp:DropDownList ID="stock" CssClass="stock-dropdown" runat="server" AutoPostBack="true" AppendDataBoundItems="true"  Width="15%"/>

Hyperlink:

<asp:HyperLink runat="server" CssClass="stock-hyperlink" Text='<%# Eval("FOOD_NO")%>' data-foodno='<%# Eval("FOOD_NO")%>' NavigateUrl="#"' />

JavaScript:

$(function() {
    $(".stock-hyperlink").click(function(event) {
        event.preventDefault(); //prevent default link behavior

        var stockVal = $(".stock-dropdown").val(); //retrieve dropdown's selected value
        var url = "";

        if (stockVal != "")
        {
            switch(stockVal)
            {
                case "PASTA":
                    url = "../FOOD_Rep/FOOD_Rep";
                    break;
                case "Source":
                    url = "../FOOD_Ing/FOOD_Ing";
                    break;
                case "Brand":
                    url = "../FOOD_Brd/FOOD_Brd";
                    break;
            }
            url += ".aspx?FOOD_NO=" + $(this).data("foodno") + "&FOOD_ID=" + $("#GROUP_ID").val();

            var winopen = window.open(url, 'Memo', ' left=50, screenx= 10, width=1360,height=820,scrollbars=1,resizable=1,toolbar=0');
            winopen.focus();
        }

    });
});

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

Why does the appearance of ASP.NET login change between debugging and deployment?

Out of the blue, I noticed a sudden change in my project. Despite working on it diligently for over a month, I encountered an unexpected issue. The login screen in Visual Studio, which typically appears as the default setting during development, now displa ...

Fuzzy text in drop-down box on Chrome, clear on Firefox

I've encountered an issue with a dropdown menu in Google Chrome where the content appears blurry, while it displays correctly in Firefox. The problem arises when the dropdown exceeds a certain height, and I've tried setting a max-height with over ...

a guide on accessing key value elements within an array using Ionic 3

Just diving into the world of Ionic, I am currently working on a task to showcase products on the cart page that have been added to the cart. Upon fetching data from a REST API, I can see the response below in the console. "items": { "29.2.2.0.YTowOnt ...

What is the reason behind the non-exportation of actions in Redux Toolkit for ReactJS?

Currently, I am utilizing @reduxjs/toolkit along with reactjs to create a shopping cart feature. However, I am encountering an issue when attempting to export actions from Cart.js and import them into other files like cart.jsx and header.jsx. The error mes ...

How can I ensure that the state is only updated after the map function has finished executing in React?

I am encountering an issue with updating the state after mapping over an array of ids using an async function. The goal is to store the result in newArr and then update the state via setState. However, the state is being updated before the mapping operatio ...

I'm encountering an issue when trying to build a React application

Unable to perform EPERM operation, the command "mkdir c:" is not found when trying to create a React app using npx create-react-app myapp ...

Cascade function with several parameters

I'm looking to utilize a cascade function with multiple parameters: // Cascade function (function ($) { $.fn.cascade = function (options) { var defaults = {}; var opts = $.extend(defaults, options); return this.each(functi ...

steps to verify the status of a sent request

I am utilizing the contenteditable property in a p tag. My code is as follows: <p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px ">&l ...

Creating a 3D cube with visual graphics as its faces using Three.js

I've been experimenting with different solutions but haven't had any luck finding a solution online. The error I'm encountering when running my program is: XMLHttpRequest cannot load file:///C:/Users/winst/Documents/Programming%20Projects/Mi ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

Ways to Insert Text and Values into an Array

{{ "user": "randomuser", "message": "require assistance" }, { "user": "automated assistant", "message": "do you need any help?" }, { "user": "randomuser", "message": "another inquiry" } I am seeking to extract additional paragraphs ...

How to Implement a Loop Inside a JavaScript Alert or Prompt?

Seeking clarity: Is it possible to embed code into an alert() or prompt()? For example, is there a way to include a loop or add data to the alert() or prompt just before execution or during execution? -Appreciate any help ...

Utilizing Class Methods within an Object (Node.js)

Seeking to streamline my code and reduce the number of if statements, I've been working on optimizing this code within a Class. if (spot.charAt(1) === "P") this.#getMovesPawn(row, col, validMoves); if (spot.charAt(1) === "N") this.#getMovesKnight(row, ...

"electron-builder - initially designated for building app for Mac only, but now configured to build for both Mac

This is my first attempt at creating an electronjs app, so I may not have a full grasp on what I'm doing. I've been following the instructions on GitHub and also this guide from Medium. Here's a snippet of my package.json: { (package.jso ...

I am currently working on creating a shopping cart that includes a delete button for removing items with just a click

I am currently working on developing a shopping cart feature that includes a remove button to delete items when clicked. I have achieved this using the filter method. However, I am facing an issue where after deleting an item and then adding it back, the ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

Utilizing jQuery UI Slider for Calculating Percentage

I recently worked on an example where I incorporated 5 sliders, which you can see here: Example: http://jsfiddle.net/redsunsoft/caPAb/2/ My Example: http://jsfiddle.net/9azJG/ var sliders = $("#sliders .slider"); var availableTotal = 100; ...

Adjusting the sensitivity of mousewheel and trackpad using JavaScript

I am currently utilizing CSS3 to smoothly move a div up and down based on the direction of scrolling. By monitoring the mouse wheel event, I can detect when a user scrolls down and trigger a CSS3 transition to slide the div up. However, I am encountering a ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...