How can I use VB codebehind in ASP to display a dialog box to the user asking for a yes or no response?

I am faced with a scenario where a user has chosen a product, the system has retrieved the product record, and the backorder flag has been set. I need to inquire if the user still wants to proceed with including the product in the order. However, I am struggling to find a clear example of implementing this within an IF statement.

Here is my snippet of VB Code:

    Dim backorder = myDataTable.Rows(0)("backorder").ToString()
    If backorder = "True" And <somehow prompt the user about including it in the order> Then
       'do something
    End If

And here is my JavaScript code in the ASPX file:

    <script type = "text/javascript">
     function Confirm() {
         var confirm_value = document.createElement("INPUT");
         confirm_value.type = "hidden";
         confirm_value.name = "confirm_value";
         if (confirm("Selected item is on temporary back order. Do you want to include it on this order?")) {
             confirm_value.value = "Yes";
         } else {
             confirm_value.value = "No";
         }
         document.forms[0].appendChild(confirm_value);
     }
</script>

I can retrieve the variable added by JavaScript to the page in VB, but I am having trouble understanding how to trigger the JavaScript function to prompt the user. Any guidance or examples would be greatly appreciated.

Answer №1

To implement the RegisterStartupScript method in your code, follow these steps:

Sub ProcessOrder()

    'Add your code to process the selected products here...
    Dim orderResponse As String = hdnConfirmResponse.Value.Trim()
    If selectedItem.BackOrdered Then
        If orderResponse = "" Then
            Dim clientScript As ClientScriptManager = Page.ClientScript

            ' Specify the name and type of the client scripts on the page.
            Dim scriptName As String = "ConfirmScript"
            Dim scriptType As Type = Me.GetType()

            ' Check if the startup script is already registered.
            If (Not clientScript.IsStartupScriptRegistered(scriptType, scriptName)) Then
                Dim scriptText As String = "Confirm();"
                clientScript.RegisterStartupScript(scriptType, scriptName, scriptText, True)
            End If
        Else
           If orderResponse = "yes" Then 
               'ADD THE CONFIRMED BACKORDERED ITEM TO THE ORDER
           End If
        End If
    End If

End Sub

Answer №2

It's a bit strange to have to answer my own question, but after combining mjw's suggestion with some additional research on my JavaScript attempt, I finally found a solution. Instead of letting JS create the hidden field, I decided to add it directly to the HTML.

    <asp:HiddenField  runat="server" id ="confirm_value"/>

Updated VB code:

    If myDataTableFrame.Rows.Count > 0 Then
                Dim backorder = myDataTableFrame.Rows(0)("backorder").ToString()
                If backorder = "True" And confirm_value.Value <> "Yes" Then
                    Dim cs As ClientScriptManager = Page.ClientScript
                    ' Checking if the startup script is already registered
                    If (Not cs.IsStartupScriptRegistered(Me.GetType(), "ConfirmScript")) Then
                        Dim cstext1 As String = "Confirm();"
                        cs.RegisterStartupScript(Me.GetType(), "ConfirmScript", "Confirm();", True)
                    End If
                    Return
                Else
                    confirm_value.Value = "No"
                    ...

Updated JavaScript: Referencing ASP.NET set hiddenfield a value in Javascript. I also added functionality to click the button again if the user selects "OK".

<script type = "text/javascript">
     function Confirm() {
         if (confirm("Selected item is on temporary back order. If you want to include it on this order click OK, then resubmit it?")) {
          //had to resort to this to find hidden field rather than document.getElementById('confirm_value')
             var x = document.getElementById('<%= confirm_value.ClientID%>');
             x.value = 'Yes';
             //re-click the button
             document.getElementById('<%=bttnadd.ClientID%>').click();
         } else {
             var x = document.getElementById('<%= confirm_value.ClientID%%>');
             x.value = 'No';
         }
     }
</script>

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

Determine the mean value by examining specific dates

I am looking to calculate the average value associated with specific dates. The data I have includes values for different dates, such as 2015/05/01 which has a value of 50. How can I write code to find the average running value on this particular date? ...

Tips on implementing Piwik JavaScript code within app.js on Express

I am trying to implement Piwik tracking on my Express website using JavaScript code. I placed the code in my app.js file but encountered an error. Here is the JavaScript code snippet: <script type="text/javascript"> var _paq = _paq || []; ...

Best practices for managing useEffect dependencies on page reload

I have a simple blog with articles. When a user clicks the edit button, a form is supposed to be filled with the article's data - title, description, body, and tags. I am using the useEffect hook to retrieve the data and fill the form based on the "id ...

Struggling to transfer information from asp.net webforms to client-side through ajax

I have been attempting to send data to the client-side using AJAX, but I am encountering an issue. The browser displays an error stating "failed to load resource", even though I have confirmed that jQuery is loaded properly. [HttpGet] public string Get ...

Navigating JSON Data with ES6 Iteration

Issue Description There are two APIs I am working with. The first one, let's call it API #1, provides JSON data related to forum posts as shown below: [{ "userId": 1, "id": 10, "title": "Tt1", "body": "qBb2" }, { "userId": 2, ...

Both of the radio buttons in Material-UI have been selected

I have a unique document that showcases an implementation of RadioGroup, FormControlLabel, and FormControl. Take a look at the code snippet below for reference. import React from 'react'; import PropTypes from 'prop-types'; import Radio ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

How can I design unique navigation menus using HTML, CSS, JavaScript, and jQuery?

Is there a way to create menus where clicking on a holiday/seasonal category opens up all related lists automatically? For example: https://i.sstatic.net/Nctd1.png I've been searching online for submenu options but haven't found the right metho ...

Utilizing jQuery for dynamic horizontal positioning of background images in CSS

Is there a way to set only the horizontal background property? I've tried using background-position-x and it works in Chrome, Safari, and IE, but not in Firefox or Opera. Additionally, I would like to dynamically set the left value of the position. ...

Execute Jquery ajax only on the initial invocation

When I am using ajax post in jQuery to build a portion of a page, I am encountering an issue where it only runs once. Below is the code snippet I am working with: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

Learn how to serialize and submit all form components within a specified element using AJAX

I am attempting to serialize and post all form elements that may originate from either within a <form> element, or any other elements such as divs, trs, etc. In essence, my form can be structured in two ways: <form id="frm1"> Name: ...

Utilizing various AngularJS filters with multiple input sources

Looking to enhance my user array filtering process with two input boxes. Here's how the array is structured: $scope.users = [{ id: 1, fname: 'Sophia', lname: 'Smith', email: '<a href="/cdn-cgi/l/email ...

Why isn't Freichat displaying the name of the user who logged in?

After creating my own small social networking site, I decided to add a chat script called freichat. However, I am facing an issue where when a user logs in, their name appears as "Guest102" instead of their actual name. I am quite confused by this problem ...

What is the best way to access a key from an object within the map function?

What is the method to extract the key from an object in ReactJS? {this.state.data.map((object, index) => ( <div>{Object.keys(object)}</div> ))} For example, if this.state.data contains: [{mykey1:23},{mykey2:24},{mykey3:34}] T ...

"Enhance your website's tracking capabilities by integrating jQuery with

Last week, everything was working perfectly fine and I hadn't made any changes to the code or settings. The google analytics javascript file is loaded using the .htaccess file, ensuring it is consistently used for all pages without any issues. However ...

My React app experienced a severe crash when trying to render an animation in L

Currently, I am working on a React application that was set up using Vite. I recently incorporated an animation using Lottie, and although I was successful in implementing it, I encountered a problem when navigating between different pages of my applicati ...

Get the value of an HTML element

Is there a way to retrieve the value of an HTML element using PHP or JavaScript, especially when the value is dynamically loaded from another source? I have tried using jQuery with the DOM ready event, but often encounter the issue where the element's ...