Whenever I attempt to retrieve content from asp.reportviewer using Javascript, it consistently returns null

I am looking for a way to directly print the content of a reportviewer without saving it as a PDF, Excel, or Word file. After doing some research on Google, I found a solution that involves the following code:


<script language="javascript" type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
    function printdiv(printpage) {
        var headstr = "<html><head><title></title></head><body>";
        var footstr = "</body></html>";
        var newstr = document.getElementById(printpage).innerHTML;
        var oldstr = document.getElementById("body1").innerHTML;
        document.getElementById("body1").innerHTML = headstr + newstr + footstr;
        window.print();
        document.getElementById("body1").innerHTML = oldstr;
        return false;
    }

<div id="body1">
    <input name="b_print" type="button" class="ipt" onclick="printdiv('div_print');" value="Print" />
<div id="div_print">
<rsweb:ReportViewer ID="ReportViewer1" runat="server" Width="944px" ShowPrintButton="true" SizeToReportContent="True" AsyncRendering="false" ></rsweb:ReportViewer>
</div>

However, when I tried implementing this code, I encountered an error message stating 'Cannot read property 'innerHTML' of null'. What could be causing this issue?

Answer №1

For optimal performance, make sure to place your JavaScript code at the end of the body tag. If you find that your script is being executed before the necessary elements are loaded, it may be because the element with the id body1 has not been defined yet. To fix this issue, you can also include your script in the head section using a script tag with an src attribute.

<head>
  <script src="my_script.js"></script>
</head>
<body>
  <div id="body1"></div>
  ...
  <script type="text/javascript">
    function printdiv(printpage) {...}
  </script>
</body>

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 Pagination in Elasticsearch with MongoDB and ExpressJS

Despite my efforts to find a solution online, I have not yet come across anything that helps me achieve what I need. This is my first time working with ElasticSearch, and I am relatively new to Node.js and MongoDB as well. Following a tutorial, I impleme ...

Leveraging Masonry.js with dynamically created divs using jQuery

Recently, I discovered Masonry.js and was excited to incorporate it into my projects. To test my skills, I decided to create a page that would display 16 divs with random heights and colors every time I clicked a button. However, I'm encountering an i ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

best practices for sending multiple requests using node js

I have a list of 4 URLs, each containing JSON data. How can I iterate through these URLs? Example: URLs = [ "", "", "", ""]; Each URL contains JSON data for one student as follows: { date: 08/05/2014 stude ...

Steps for removing an embed after a set time period

I've been using message.delete({timeout: 3000}) to remove messages with the prefix. Now I'm wondering how I can also delete the embed I sent after a certain amount of time. if (!args[0]) return message.channel.send({ embed: { color: 1677720 ...

What could be causing my C# function to not be triggered by AJAX?

I am attempting to invoke this specific C# method: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static string getJSONdata() { string jsonString = ""; using (SqlConnection con = new SqlConnection(conn ...

Alter regular expression matches within the new string replacement

I am having an issue with using regex to extract URLs from a text and then modifying all the matches within the replacement string using a function. Below is a simplified example of what I am trying to accomplish. Is it possible to achieve something lik ...

Iterate through an array to calculate the total sum of elements within subarrays associated with distinct entities

Apologies if the title was a bit unclear. Let me try to elaborate on the question: I have an array with some sample data as shown below: const data = [ { name: "Bob", items: [1] }, { name: "charlie", items: [1,2] }, { name: "Ch ...

When navigating back to the Homepage from another page, React displays the Homepage

Recently, I started learning React and following the Traversy crash course along with an additional video on React router 6+. My route setup looks like this: import { BrowserRouter as Router, Route, Routes } from 'react-router-dom' return ( &l ...

Tallying the number of words delimited by a comma

Here is how my counter function is structured: function count() { var value = ids.val(); return (value == '') ? 0 : value.replace(/\s,?|,$/g, '').split(',').length; } After checking the returned value, data is ...

Unravel JSON using JavaScript on the web

I encountered an issue while running this code and trying to decode it: var data = JSON.parse({"forms":[{"url":"example.com/example","name":"example"}]}) document.getElementById("name").innerHTML=data.forms.name Instead of the expected value, the returne ...

Modify the CSS using JavaScript after a brief delay

I'm creating a homepage that includes animations. Inside a div, I initially have display: none, but I want it to change to display: block after a few seconds. I've been trying to use JavaScript for this purpose, but I'm struggling to find th ...

Determine which button is active using Selenium

I am looking to determine which option is currently selected in the code snippet below: <div class="col-xs-12 noPadding details AdminDetails" data-value="INVITE" xpath="1"> <div class="col-xs-8 left"> ...

Creating multiple tables from a single set of JSON data

I've been working on dynamically creating an HTML table from JSON data. Successfully creating the table dynamically, but now I need to modify it based on new requirements. Current Progress I have an array of objects that I use to create the table a ...

Is there a way to automatically change the display of an element once the user has closed the menu?

How can I ensure that the display of an element remains unchanged when a user opens and closes my website menu using JavaScript? ...

Leveraging a tool to dynamically modify the styles of the active elements based on user interactions

My goal is to enhance the flexibility of my service by enabling it to handle any input field dynamically. Currently, I find myself manually coding everything, which is becoming quite labor-intensive. Is there a way to pass the element object when the eleme ...

Modifying an @Input element within a component does not result in any changes being reflected in the parent component

Here is the scenario with my component: @Component({ selector: 'child' }) export class ChildComponent { @Input() childObject: ChildObject; changeObject(newObject: ChildObject){ childObject = newObject; } } After calling ...

Request to api.upcitemdb.com endpoint encountering CORS issue

This code may seem simple, but for some reason, it's not working as expected. What I'm trying to achieve is to call the GET API at: I want to make this API call using either JavaScript or jQuery. I've attempted various approaches, but none ...

jQuery cannot access a hidden CSS property

I'm working on a form for my new project and have assigned the same class to all input fields. In my CSS file, I've set the text to be capitalized and it displays correctly. However, when I use jQuery's .val() to get the value of the field, ...

In Typescript, how can we reverse the order of an enum

I am encountering a particular challenge with the following code snippet: enum MyEnum { Colors = 'AreColors', Cars = 'AreCars', } const menuTitle = ((obj: MyEnum) => { const newObj = {}; Object.keys(obj). ...