Once the printing button is clicked, shift your attention to a different button

I have a button that is designed for printing. When the print button is clicked, I want the focus to then shift to another button. However, my current code is not functioning properly.

The error message displayed in Firebug reads

TypeError: document.getElementById(...) is null
. The printing process itself completes successfully, but the focus does not move to the "btn_CR" button afterwards.

How can I ensure that after printing, the focus is automatically directed to the "btn_CR" button? Do I need to incorporate server-side scripts or can this be resolved with JavaScript? Your assistance is greatly appreciated.

Here is a snippet of my ASPX code:

<asp:Content ID="AdminContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Panel ID="print_Client_registration" Visible="false" runat="server">
        <div id="printIt">            
            <div style="width: 260px;font-family:Arial,Helvetica, sans-serif;">
                <div style="text-align: center; width: 100%; font-size: 15px;"><b>
                    <asp:Label ID="lblClientId" runat="server" /></b></div>
                <div style="text-align: left; width: 100%; font-size: 13px;"><b>Name:</b>
                    <asp:Label ID="lblName" runat="server" /></div>
            </div>
        </div>            
        <asp:Button ID="btn_print" runat="server" ClientIDMode="Static" Text="Print" OnClientClick="printPage();"/>        
        <div>
            <table class="nostyle">
                <tr>
                    <td><input type="button" id="btn_CR" runat="server" value="Client Register" onclick="window.location.href = 'NewClientRegister.aspx'" /></td>

                </tr>
            </table>
        </div>
    </asp:Panel>
    <script type="text/javascript">
        var NextFocusButtonId = <%=btn_CR.ClientID%>;
    </script>
    <script type="text/javascript" src="../scripts/print.js"></script> 
</asp:Content>

An important note: the printPage() function belongs to the external "print.js" file.

function printPage() {
    var headstr = "<html><head><title></title></head><body>";
    var footstr = "</body>";
    var newstr = document.getElementById("printIt").innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = newstr;
    window.print();
    document.body.innerHTML = oldstr;
    document.getElementById('<%=btn_CR.ClientID%>').focus();
}

After following suggestions, I updated the code from:

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

To simply:

document.getElementById('btn_CR').focus();

Despite this adjustment, the same error persists -

TypeError: document.getElementById(...) is null
.

Answer №1

Avoid using the inline expression <%=btn_CR.ClientID%> in a .js file. Consider this alternative approach:

document.getElementById('btn_CR').focus();

Furthermore, within your printPage function, you are attempting to access

getElementById(printIt').innerHTML
. This will not work as there is no element with an ID of 'printIt', resulting in a broken null.innerHTML.

Answer №2

The code snippet <%=btn_CR.ClientID%> is not being translated within the print.js file. To address this issue, you can use a simple trick by placing this code just before the inclusion of the JavaScript file. For example:

 <script>
 var NextFocusButtonId = <%=btn_CR.ClientID%>;
 </script> 
 <script type="text/javascript" src="../scripts/print.js"></script> 

Then, inside your print.js file, you can include the following:

  document.getElementById(NextFocusButtonId).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

Developing an intricate nesting structure for an object

this is my code snippet: "book" => {b:{o:{o:k:{'end':true} could someone please provide an explanation or a helpful link for this? const ENDS_HERE = '__ENDS_HERE' class Trie { constructor() { this.node = {}; } insert(w ...

Navigating the Google Maps API: Implementing Scroll Zoom to Focus on a Single Marker

I'm looking for a solution for my project where the scroll zoom function will focus on zooming in on a marker or specific point rather than defaulting to the cursor. The current behavior is that the scroll zoom always centers on the cursor. Can anyone ...

The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly. Here is my code: .css { font-weight: bold; ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

Incorporate validation features within a jQuery method

I am struggling with some HTML and jQuery code that generates links based on user input. HTML <input type="text" id="text" placeholder="Enter text" autofocus /> <a id="link1" class="btn btn-info" href="#" target="_blank"> Search 1 </a> ...

What is the best approach to incorporate this D3.js HTML element into my AngularJS project for easy manipulation?

I've been experimenting with creating graphs using the D3.js graphical library for Javascript on my webpage. Currently, I can draw a gray line on an SVG using HTML and a red line using Javascript on a new SVG container created in Javascript. However, ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

After ajax, trigger change event

Can anyone assist me in combining multiple functions within the same form using AJAX? The purpose of the form is to prenote a new "meeting" and it consists of an input for the date and a select dropdown for choosing the operator. FORM CODE: <div id=&qu ...

Eliminate the flickering effect on the dropdown menu

Is there a way to eliminate the annoying 'flicker' effect on my menu? Whenever I click on 'Dropdown 1', I notice that Test 1 and Test 2 flicker. My assumption is that this is due to my use of the !important declaration. Any suggestion ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

When employing `queryParams` in Angular routing, the URL will automatically replace `%` with `%25`

When trying to use queryParams for navigation in Angular routing, I encountered an issue. <a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a> The d ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

Filtering URLs using Firefox extension

As the page loads, multiple HTTP requests are made for the document and its dependencies. I am looking to intercept these requests, extract the target URL, and stop the request from being sent if a specific condition is met. Additionally, plugins may als ...

How can I pass an array from HTML to Node.js and subsequently store it in MongoDB?

Looking to combine the values of longitude and latitude into one array for input, then store it in the database. While there are plenty of examples on handling arrays, most of them are based on PHP. Check out the following code snippet: HTML <html> ...

Require a selection from the menu on the right side needed

I am looking to have the logout link displayed on the far right when the other menu items are hidden. Currently, it is appearing in the center. Is there a way I can make it show up on the right? <div class="nav-content container"> &l ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

Top spot for placing a file containing a polyfill to ensure cross-browser compatibility in JavaScript projects

Curious about the best location within a React / Redux app (built with create-react-app) to store custom polyfill files for browsers that do not support certain features. I specifically require Array.prototype.includes and String.prototype.startsWith, as ...

Ways to retrieve HTML tags from a website's DOM and shadowDOM

I am currently working on a project using NodeJS where I need to extract the HTML structure of multiple websites. However, I am facing some challenges with this task. My goal is to retrieve only the HTML structure of the document without any content. It is ...

When the condition within the click function is met, concatenate the variable

I'm currently working on a function that involves adding "http://" to the variable 'bar' if it's not already included. This modified 'bar' value will then be sent via ajax to be inserted into the database and also displayed ba ...

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...