One function being triggered by multiple buttons to carry out various tasks

I have two buttons that call the same function. The btnUpdate button needs to execute this function, while the btnSave button does not need to execute it.

<script type="text/javascript>
function Update_New() {
  if (document.getElementById("btnUpdate").value == 2) {
    var update_confrimation = confirm("Are you sure you want to Update?");
    if (update_confrimation == true) {
      return true;
    } else {
      return false;
    }
  }

CODE FOR BUTTONS

 <asp:Button ID="btnSave" runat="server" Text="SAVE" OnClick="btnSave_Click" OnClientClick="return Update_New()" value="1" />
<asp:Button ID="btnUpdate" runat="server" Text="UPDATE" OnClick="btnUpdate_Click" OnClientClick="return Update_New() " value="2" /

WHEN I CLICK UPDATE, NO ACTION TAKES PLACE The problem is that VALUE IS NOT DEFINED in JavaScript (@document.getElementById(“btnUpdate”).value)

Answer №1

Instead of directly calling a function, you can pass parameters to the function when making the call. See example below:

HTML:

<asp:Button ID="btnSave" runat="server" Text="SAVE" OnClick="btnSave_Click" OnClientClick="return Update_New(true)" value="1" />
<asp:Button ID="btnUpdate" runat="server" Text="UPDATE" OnClick="btnUpdate_Click" OnClientClick="return Update_New(false) " value="2" />

JavaScript:

<script type="text/javascript">
    function Update_New(isnew) {
        if (!isnew) {
            var update_confrimation = confirm("Are you sure you want to Update?");
            if (update_confrimation == true) {
                return true;
            }
            else {
                return false;
            }
        }
    }
</script>

Note: To access server controls, use the method shown below:

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

Answer №2

When working with ASP controls in JavaScript, it's important to note that you cannot directly access them using document.getElementById(). To enable this functionality, you can set the control's ClientIDMode property to one of the following values:

  1. AutoID
  2. Static
  3. Predictable
  4. Inherit

For example, consider the script below:

<script type="text/javascript">
  var seasonalSports = new Array("None selected",
                                 "Tennis",
                                 "Volleyball",
                                 "Baseball",
                                 "Skiing");

  function DisplaySport(x) {
      document.getElementById("SelectedSport").innerHTML
      = seasonalSports[x];
  }    
</script>

<asp:DropDownList ID="DropDownList1" runat="server" 
                  onchange="DisplaySport(this.selectedIndex);">
  <asp:ListItem Value="Select a season"></asp:ListItem>
  <asp:ListItem Value="Spring"></asp:ListItem>
  <asp:ListItem Value="Summer"></asp:ListItem>
  <asp:ListItem Value="Autumn"></asp:ListItem>
  <asp:ListItem Value="Winter"></asp:ListItem>
</asp:DropDownList>
<br />
<asp:Label ID="SelectedSport" runat="server" ClientIDMode="Static">
</asp:Label>

Answer №3

To ensure a unique client ID for the button element, you have two options:

1. Set the ClientIDMode property of btnUpdate to Static.

2. Alternatively, use the

getElementById("<%=btnUpdate.ClientID%>")
method.

Answer №4

Despite having accepted an answer and all previous answers working correctly, I would like to point out a mistake for your awareness. When examining your provided markup:

<asp:Button ID="btnSave" runat="server" Text="SAVE" OnClick="btnSave_Click" OnClientClick="return Update_New()" value="1" />
<asp:Button ID="btnUpdate" runat="server" Text="UPDATE" OnClick="btnUpdate_Click" OnClientClick="return Update_New() " value="2" /

You are utilizing a property called value which is not recognized by Asp.Net server control. Refer to this MSDN link Button Property. Even if specified as a custom attribute, it will not be rendered due to the Button's Text property getting converted to value in HTML rendering, leading to conflict. In this context, it should show Save/Update instead of 1/2, respectively.

A more suitable approach would involve using a data-attribute to store additional data values for client-side use.

HTML

<asp:Button ID="btnSave" runat="server" Text="SAVE" OnClick="btnSave_Click" OnClientClick="return Update_New()" data-attr="1" />
<asp:Button ID="btnUpdate" runat="server" Text="UPDATE" OnClick="btnUpdate_Click" OnClientClick="return Update_New()" data-attr="2" />

Javascript

<script type="text/javascript">
    function Update_New(obj) {
        if (obj != undefined) {
            if (obj.dataset.attr == 2) {
                var update_confrimation = confirm("Are you sure you want to Update?");
                if (update_confrimation == true) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }
    }
</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

Utilizing all Four Quadrants in a Scatter Plot with Recharts

I'm currently utilizing Recharts to visualize data in a react application. My goal is to display all four Cartesian quadrants in the graphing process. Here is the code snippet I am using: // Code removed for brevity I am striving for a result simila ...

Issue with fetching API data and sending it to the Node server

My node backend is all set up and running smoothly for GET requests, but I'm facing an issue with POST requests as the data doesn't seem to be getting sent to the backend. Here's the code snippet: fetch("http://localhost:3000/", ...

HTML5: Enhancing Video Playback on the iPad with Custom Zoom Controls

I've customized a smaller UIWebView specifically for the iPad, and I've created my own HTML5 controls for the video playback. However, when I try to maximize the video, all I see is a black screen instead of the actual content. The audio still pl ...

Looking to pull out the .js URL from a website?

Looking to extract a .js link from a webpage. How can I locate the JavaScript page link within the source code of a web page? I am specifically interested in a Java-based solution for this task. ...

Transferring information from nopCommerce to Umbraco version 7

During the process of developing a new Umbraco website for a client, I am tasked with transferring all content (products, categories, product images, etc) from nopCommerce to Umbraco 7. To maintain relationships and mappings between products and categories ...

"Experience the power of using Selenium with Node.js in an asynchronous function

I'm currently developing a simple program that retrieves the titles of all the links when conducting a search on Google using Selenium Take a look at the code below: const {Builder,By, Key, until} = require('selenium-webdriver'); driver = ...

Get the identifier from a database table for future use

Currently, I am attempting to retrieve the auto-increment value P_id from the table P_identity in order to store it in the Communication table. Unfortunately, I seem to be encountering an error. "Error :System.Data.SqlClient.SqlException (0x80131904): C ...

switch hover interactions to click

I'm looking to change from hover to mouse click, and here is a snippet of the code: HTML <li class="has-dropdown"> <a href="#">Click Me</a> <ul class="dropdown"> <li> ...

Reading RFID data in Arduino via USB serial communication

Currently, I am engrossed in an Arduino project that involves saving a timestamp and RFID code to the ROM on the Arduino board when an RFID tag is scanned. The RFID data is retrieved through the use of Serial.read(), but now I am faced with the challenge o ...

The function .jqGrid() cannot be found when trying to call it on an .aspx webpage

I successfully integrated a JQgrid into my Visual Studio 2010 project, but I encountered an error when trying to add it to my Visual Studio 2013 web project. The error message reads: $(...).jqGrid is not a function empty string passed to getElementById H ...

Exchange SMS messages between server and web application

I'm currently based in Kenya and finding the pricing of Twilio to be quite high. My goal is to send and receive SMS messages, save them in a database, and showcase them on a web app. Do you think it's possible to create this using node.js? What w ...

It's not possible to add additional options to the select input in a react

Hi there! I'm currently facing an issue while trying to retrieve a list of options from the backend, map them to another list of options, and add them to a main list. Unfortunately, my attempts have not been successful. Could anyone offer some advice ...

Error in Express Dynamic Routes: Cannot Locate Property 'Concat'

I'm attempting to generate routes dynamically in nodejs using express by retrieving the pages from a mongodb database. The code inside routes.js looks like this: module.exports = function(app, passport) { Page.find(function(err, leroutedata){ ...

What is the best way to display text in html based on a specific condition being fulfilled in AngularJS?

Is there a way to display text in an HTML page only when a certain condition in an input box is satisfied, and hide it otherwise? I am currently using AngularJS and here is a snippet of my HTML code: <form novalidate="" class="simple-form">conditi ...

When attempting to trigger a function by clicking a button in Angular 8 using HTTP POST, nothing is happening as

I've been struggling to send a POST request to the server with form data using Observables, promises, and xmlhttprequest in the latest Angular with Ionic. It's driving me crazy because either I call the function right at the start and the POST wo ...

Why is it that when I return a JSONResult from an overridden JSON method it doesn't function, but a ContentResult does

Recently I encountered an unusual situation while attempting to override the Json method of a Controller class in order to utilize JSON.net contract resolver. Strangely, everything works as expected when I return an object of ContentResult and cast it to A ...

Navigate to a specific line in Vscode once a new document is opened

Currently, I am working on a project to create a VS Code extension that will allow me to navigate to a specific file:num. However, I have encountered a roadblock when it comes to moving the cursor to a particular line after opening the file. I could use so ...

How can we transfer a jQuery value from an input field without using a single

This task may seem challenging. How can single quotes be eliminated from a variable when passed directly to another variable? I am using jQuery variable $("#test").val() to extract the value from an input below <input type="text" ...

Deleting a single row in a GridView using a DropDownList in ASP.NET

Welcome to my design portfolio <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="newsamplecomb._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xh ...

What steps do I need to take to adjust my code so that the div function is hidden upon the second click

, I have provided my code as a beginner who is learning on the go. The code showcases a function that triggers on click and loads content accordingly. However, the desired functionality includes hiding the content on the second click and maintaining an "a ...