Implementing a JavaScript confirmation based on an if-else statement

I need to display a confirmation dialog under certain conditions and then proceed based on the user's response of yes or no. I attempted the following approach.

Here is the code in aspx:

<script type="text/javascript>
  function ShowConfirmation() {
    if (confirm("Employee already exists. Continue?") == true) {
      document.getElementById("hdn_empname").value = 1;
    }
  }
</script>

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

And here is the code in cs:

if (reader2.HasRows)
{  
    Page.ClientScript.RegisterStartupScript(this.GetType(), "showAlert", "ShowConfirmation();", true);
}
else
{
    hdn_empname.Value ="1";
}

if ((hdn_empname.Value)=="1")
{
   //execute some specific code
}

However, during debugging, hdn_empname shows value="".

Could anyone assist me with this issue?

Thank you in advance.

Answer №1

Give it a try You have to use the ClientID

document.getElementById('<%=hdn_empname.ClientID%>').value = 1;

I discovered the main issues

The hidden field values will be assigned after the if condition is called.

Update :

Therefore, you should execute your logic on the JavaScript side using ajax

if (confirm("Employee already introduced. Continue?") == true) {

//some code to execute
    }

Answer №2

Do you know where your breaking point lies? Once reader2.HasRows is true, your javascript will be activated. However, the value is only set on the client side and you will receive the result after a postback.

Answer №3

hdn_empname is the ID for server controls, which is different from the client-side ID. To get the client-sided ID, you need to use ClientID.

Try this:

document.getElementById('<%=hdn_empname.ClientID%>').value = "1";

You don't need to compare

if (confirm("Employee Introduced already.Continue?")) 

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

Intersection Observer API is not compatible with the functionality of the navigation bar

Having trouble with the Intersection Observer API. Attempting to use it to show a nav-bar with a white background fixed to the viewport once it scrolls out of view. Initially tested using console.log('visible') successfully to determine visibili ...

Accessing dynamic elements in Internet Explorer 7 and 8 using jQuery

I have generated an HTML element dynamically using jQuery. Unfortunately, I am facing difficulties accessing the element utilizing jQuery selectors in IE7/IE8. For example: var id = 45; var $comment = $('#comment-'+id); // dynamically created ...

Adding HTML to a webpage through the use of JavaScript's .innerHTML functionality

Currently in the process of creating a website template, I have made the decision to experiment with using an external JS file for inserting HTML at the top of the page to streamline navigation (eliminating the need for manual copying and pasting). My att ...

Error encountered while deserializing with Newtonsoft.Json JsonConvert

I successfully serialized a complex object using Newtonsoft.Jsonconverter's SerializeObject method. However, when I tried to deserialize the same object with the DeserializeObject method, I encountered the error message: "An item with this key has alr ...

Hidden IFrame for Jquery File Upload

I was looking for a quick guide on setting up an AJAX-style file upload using a hidden iframe. Below is the section of HTML code related to the form: <div id = "file" class = "info"> <form id="file_upload_form" method="post" enctype=" ...

Superimpose a canvas onto a div element

I'm struggling to overlay a canvas on top of a div with the same dimensions, padding, and margins. Despite using position: absolute and z-index as suggested in similar questions, the canvas keeps appearing underneath the div. Here's my current co ...

Caution: The server is expected to have a matching navigation within the div tag

I am currently working with next.js framework and encountering the following error message: "Warning: Expected server HTML to contain a matching nav in div". Below is a snippet of my code: export default function Member() { const router = useRouter(); ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Dropped down list failing to display JSON data

I created a website where users can easily update their wifi passwords. The important information is stored in the file data/data.json, which includes details like room number, AP name, and password. [ {"Room": "room 1", "AP nam ...

Guide on launching Selenium within an already open browser using manual settings

Issue The default behavior of Selenium is to open a new browser window during execution. However, I am looking to have Selenium operate within an existing browser session (preferably in Google Chrome). While there are solutions available in Java and Pytho ...

Invoke Ajax utilizing an Identifier

How do I add an ID to Ajax: function callAjax() { jQuery.ajax({ type: "GET", url: "topics.php?action=details&id=", cache: false, success: function(res){ jQuery('#ajaxcontent').html(res) ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

Evaluating the functionality of express.js routes through unit testing

Just dipping my toes into the world of express and unit testing. Take a look at this code snippet: const express = require('express'); const router = express.Router(); const bookingsController = require("../controllers/bookings"); router .r ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...

Guide to setting a dynamic print style without affecting the screen media

In my report, there is a details section below. The screen provides instructions to view the details with a button that toggles the list's visibility. When printing the report, I only want the instructions to show if the list is visible. If the list ...

Is React-Apollo encountering a 404 network error?

I am currently exploring React-apollo and attempting to implement Server-side rendering with apollo, but I keep encountering a 404 error. Despite confirming that my graphQL endpoint is functional. Here is the specific error message: { Error: Network erro ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

I'm interested in exploring different database implementation patterns in JavaScript. What kinds of approaches can I consider?

As someone who is relatively new to exploring JavaScript, I have been immersed in experimenting with a node test app and MongoDB. I am eager to delve into the database aspect of the app but finding myself uncertain about the most commonly used patterns in ...

Troubleshooting the Nextjs-blog tutorial loading issue on localhost:3000

Looking to delve into Nextjs, I decided to start by following a tutorial. However, every time I attempt to run 'npm run dev', the local host just keeps loading endlessly. Upon inspecting and checking the console, there is no feedback whatsoever. ...

Matching with Regex beyond the limits

Trying to extract a body tag using regex and then replace it with an appended string. However, encountering an issue where the regex is selecting more content than intended. regex: /<body.*[^>]>/i test string: <bla bla ><body class=&apo ...