JavaScript unable to locate ASP button ID with the method "findbyelementID"

Trying to locate the ID of an ASP.Net control in JavaScript is proving challenging as it keeps showing "ID not found." While I have reviewed various related questions, they all pertain to ASP forms or similar, whereas I am utilizing DIV tags here, resulting in an error on the page.

Here is the code snippet :

<asp:Content ID="Content4" ContentPlaceHolderID="cphSubmit" runat="server">
<div id="divConfMessage" style="BORDER-RIGHT:black thin solid; BORDER-TOP:black thin solid; DISPLAY:none; Z-INDEX:200; BORDER-LEFT:black thin solid; BORDER-BOTTOM:black thin solid; background-color:white;">
    <br />
    <br />
    <div style="BACKGROUND-COLOR: white;TEXT-ALIGN: center" id="confirmText"></div>
    <div style="Z-INDEX: 105;HEIGHT: 22%;BACKGROUND-COLOR: white;TEXT-ALIGN: center"></div>
    <div style="Z-INDEX: 105;BACKGROUND-COLOR: white;TEXT-ALIGN: center">
        <asp:Button ID="btnConfOK"  Width="200px" Height="25px" CssClass="gradientbutton" OnClick="btDelete_Click" Runat="server" Text="Yes"></asp:Button>
        <asp:Button ID="btnConfCancel" Width="200px" Height="25px" CssClass="gradientbutton" Runat="server" Text="No"></asp:Button>
    </div>
</div>
<script type="text/javascript" src="/_layouts/1033/jquery.js"></script>
<script type="text/javascript" language="JavaScript" src="CustomDialog.js"></script>
<script type="text/javascript" language="JavaScript">
        function ShowMessage()
        {
            DisplayConfirmMessage('Do you really want to delete this decision?',480,120);
            document.getElementById('<%=btnConfOK.ClientID%>').focus();
            //SetDefaultButton('btnConfOK');
            return false;
        }
</script>
    <asp:Button ID="btDelete" runat="server" CausesValidation="False" CssClass="gradientbutton"
    UseSubmitBehavior="False"
    OnClientClick="this.disabled=true;this.value='Please Wait...';ShowMessage();"
    Text="Delete" Width="200px"  />

EDIT:

After making the necessary adjustments, the Dialog box appears and disappears abruptly, leaving me puzzled :|, I suspect I need to include the control in the DOM but I am unsure how to achieve that within this context :|

View the tutorial link I followed Dialog box tutorial

JS script

var divWidth = '';
var divHeight = '';
var txtFirstButton = 'OK';
var txtSecondButton = 'Cancel'
    function DisplayConfirmMessage(msg,width,height)
    {
            // Set default dialogbox width if null
            if(width == null)
            divWidth = 180 
            else 
            divWidth = width;

            // Set default dialogBox height if null
            if(height == null)
            divHeight = 90 
            else 
            divHeight = height;


            // Ge the dialogbox object
            var divLayer = document.getElementById('divConfMessage');
            // Set dialogbox height and width
            SetHeightWidth(divLayer)
            // Set dialogbox top and left
            SetTopLeft(divLayer);

            // Show the div layer
            divLayer.style.display = 'block';
            // Change the location and reset the width and height if window is resized
            window.onresize = function() { if(divLayer.style.display == 'block'){ SetTopLeft(divLayer); SetHeightWidth(divLayer)}}
            // Set the dialogbox display message
            document.getElementById('confirmText').innerHTML = msg;
    }

    function SetTopLeft(divLayer)
    {
        // Get the dialogbox height
        var divHeightPer = divLayer.style.height.split('px')[0];

         // Set the top variable 
        var top = (parseInt(document.body.offsetHeight)/ 2) - (divHeightPer/2)
        // Get the dialog box width
        var divWidthPix = divLayer.style.width.split('px')[0];

        // Get the left variable
        var left = (parseInt(document.body.offsetWidth)/2) - (parseInt(divWidthPix)/2);
        // set the dialogbox position to absolute
        divLayer.style.position = 'absolute';

        // Set the div top to the height 
        divLayer.style.top = top

        // Set the div Left to the height 
        divLayer.style.left = left;
    }
    function SetHeightWidth(divLayer)
    {
        // Set the dialogbox width
        divLayer.style.width = divWidth + 'px';
        // Set the dialogbox Height
        divLayer.style.height = divHeight + 'px'
    }

    function SetDefaultButton(defaultButton)
    {
            // Set the focus on the Cancel button
            document.getElementById(defaultButton).focus();
    }

If I remove "UseSubmitBehavior="False", everything works as intended, except that clicking on Yes does not close the Dialog box

Answer №1

When using getElementById, make sure to enclose the id in quotes, as shown here:

document.getElementById('<%=btnConfOK.ClientID%>').focus();

Answer №2

Make sure to enclose the output in double quotes:

document.getElementById(<%=btnConfOK.ClientID%>)

needs to be changed to:

document.getElementById("<%=btnConfOK.ClientID%>")

Answer №3

The correct syntax to use is

document.getElementById("<%=btnConfOK.ClientID%>").focus();

To learn more about document.getElementById, click here.

Update

function ShowMessage()
        {
            DisplayConfirmMessage('Are you sure you want to delete this decision?',480,120);
            document.getElementById("<%=btnConfOK.ClientID%>").focus();
            //SetDefaultButton('btnConfOK');
            return false;
        }

If your delete button triggers a post-back, make sure to use event.preventDefault on the delete button click.

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

Have you ever wondered why the React HeroIcons architecture includes React.createElement instead of simply returning plain SVG elements?

As I integrate HeroIcons into my Next.Js app, I find myself pondering over how they have structured their package architecture. The way they return icons is like this: const React = require("react"); function ArchiveIcon(props, svgRef) { retur ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

Tips for integrating html2canvas with Vue JS?

One hurdle I encountered was the absence of a shorthand for document.getElementById in Vue. To address this, I created a custom function similar to this one. Another challenge I am currently grappling with is the perceived limitations of the html2canvas do ...

Is there a way I can utilize a for-loop and if statement in JavaScript to present the information accurately within the table?

My current task involves fetching data via AJAX and then using a for-loop and if-statement to determine which goods belong in each shopping cart. Once identified, I need to display these goods in separate tables corresponding to each customer. Although the ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

How can I extract the page's output using JQuery?

Being a rookie in this area, I am eager to learn how to extract specific content from a page using AJAX in JQuery. Currently, I have been able to fetch the data of a page and display it as text: $.ajax({ type: "POST", url: "myfile.html", su ...

What is the best way to send props to a React component?

Sorry for the inconvenience of asking for help with finding an issue in my code, but I'm facing challenges while learning React. I am attempting to pass a variable named hashRoute to a component in react. However, every time I try to access the prop ...

What is the best way to call an API within a loop using Node.js?

How can I efficiently make API calls based on page numbers in a loop? I am using the request() function for API calling, but when debugging my code, the response block is not reached and I do not get a response. Can someone please provide guidance on how ...

What steps should I follow to change the appearance of this object to match this?

Attempting to modify the value of an object nested within an array, which is in another object. The nesting might be a bit complex... Here's how it currently looks { household and furniture: [{…}, {…}], school stuffs: [{…}, {…}] } M ...

Is there a way to transform a tabulated tree into JSON using JavaScript?

I've been searching for a solution, but I have come to the conclusion that this question is quite peculiar. How can I convert the following text file using tabs for spacing: parent child child parent child grandchild grand ...

Posting Form Data with Ajax in CodeIgniter

Incorporating the CodeIgniter framework along with the jQuery Form plugin available at http://malsup.com/jquery/form/ Encountering challenges in ensuring proper functionality of a form. View <div class="row"> <div class="well c ...

There seems to be an issue with the HighCharts chart export feature as it is not showing the Navigator graph

We are currently using HighCharts version 4.2.2 http://api.highcharts.com/highcharts/exporting While going through their exporting documentation, I made a decision to not utilize their default menu dropdown. Instead, I only needed access to the .exportCh ...

Creating a Distinct Interior Array Separate from the Exterior

I'm currently working on a project that involves creating a 2D array. I want the interior elements of this array to be black while the exterior elements should be white. However, my 2D array doesn't seem to be forming correctly - it looks more li ...

Toggle the mute and unmute feature for a participant in an AWS Chime meeting

Hello everyone! I'm looking for details on the AWS Chime SDK (amazon-chime-sdk-js). Is it possible with the Amazon Chime SDK for 3 participants (Anna, John, and Lenny) in a meeting room to have Anna ignore Lenny's microphone and only hear John, ...

Is there a way to deactivate the <script> tag using CSS specifically for media queries?

When designing a website exclusively for desktop usage, I encountered the issue of it not being viewable on mobile devices. I attempted to address this problem by utilizing the code below: script { display: none; pointer-events: none; } Unfortunat ...

The page switch with a jittery effect

Could really use some assistance with this code that has been giving me trouble for quite a while now. It's a simple HTML, CSS, and JS code involving two pages. [The second page overlaps the first by default, but adjusting the z-index of the first p ...

UI-data contracts: enhancing client-side JSON data validation

I have encountered situations where the JSON data I receive from services and database calls, created by a different team, contains invalid data combinations that lead to unintended errors downstream. For example, in the case below, if the "rowContent" fi ...

You are required to select one of the two radio buttons in order to proceed with the validation process

To prevent the user from proceeding to the next page, validation is necessary. They are required to select one of the radio buttons, etc. <div class=""> <div class="radiho" style="display: block"> <input type="checkbox" name="sp ...

The code functions perfectly in the Adobe Dreamweaver Preview, but unfortunately, it is not compatible with Chrome

In the process of creating a website using Adobe Dreamweaver over the past few days, I encountered an issue with JavaScript that should activate upon scrolling. Interestingly, the script works perfectly fine when accessed through this link (), but fails t ...

The Vue Router hooks are not being activated within the component when utilizing Typescript

I've been pondering this issue for quite some time. Despite my extensive search efforts, I am still unable to figure out why the route-hooks are not working in my component: 1. The component is being loaded from RouterView: <router-view class="z1 ...