What is the solution for the error message: "[Vue warn]: Error in mounted hook: 'TypeError: document.getElementById(...) is null'" that appears in the <Root> component?

I'm facing an issue with a checkbox in my Vue.js application. Whenever the user checks this checkbox, the data property accepted changes from false to true.

My goal is to hide certain HTML elements when accepted = true. I have been attempting to achieve this by accessing the element by its id and setting display: none.

However, I keep encountering the error

TypeError: document.getElementById(...) is null
. I suspect that this is happening because my function is being executed before the page has fully loaded.

How can I resolve this issue?

Thank you for your assistance.

HTML

       <div id="acceptedTrue" >
         <form action="" class="AGBcheckbox" >
           <input
             id="checkbox"
             onkeyup="agbValidate('checkbox')"
             v-model="newContract.accepted"
             class="AGBcheckboxInput"
             type="checkbox"
             name="AGB"
             value="AGB"
           />

           <label for="AGB">
             I agree the terms and conditions
           </label>
         </form>
       </div>

vue.js

    new Vue({
      el: "#app",
      delimiters: ["[[", "]]"],
      data() {
        return {
          newContract: {
            postcode: "",
            accepted: false,
            accepted_by: "",
          },
        };
      },
      methods: {
        changeAGBview() {         
          if(this.newContract.accepted = true)  {
            document.getElementById("acceptedTrue").style.display = "none"
            }
        }
      },
      mounted() {
      this.changeAGBview()
     }

Answer №1

Have you considered utilizing the v-if directive in this scenario?

   <div id="acceptedTrue" v-if="!newContract.accepted">
     <form action="" class="AGBcheckbox" >
       <input
         id="checkbox"
         onkeyup="agbValidate('checkbox')"
         v-model="newContract.accepted"
         class="AGBcheckboxInput"
         type="checkbox"
         name="AGB"
         value="AGB"
       />

       <label for="AGB">
         I agree the terms and conditions
       </label>
     </form>
   </div>

Just a friendly reminder, since your Vue instance is connected to the element with id #app, ensure that your html content is encapsulated within this specific element.

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

Exploring Event Listeners in the World of JavaScript and/or jQuery

Is there a more sophisticated way to monitor the execution of a specific function in JavaScript or jQuery? Instead of waiting for an event like $('#mything').click(function(){ //blah }), I prefer to be notified when a particular function is trig ...

Which language is better for refreshing web pages: PHP or Javascript?

May I seek your opinion on this matter? I have the ability to refresh my page using two different methods, but I am uncertain of any potential drawbacks. Can you advise me on which one I should utilize? Edit: Specifically, I am referring to the use of he ...

Steps to seamlessly integrate puppeteer with an active Chrome instance or tab

Is there a way to connect puppeteer to an already open Chrome browser and control a specific tab? I believe it may involve starting Chrome with the --no-sandbox flag, but I am unsure of the next steps. Any assistance on this matter would be greatly apprec ...

Overuse of jQuery's preventDefault() and stopPropagation() functions

A recent discussion with a coworker revealed some contrasting coding practices, mainly concerning his extensive use of the two aforementioned methods in event handlers. Every event handler he creates follows this same pattern... $('span.whatever&apos ...

Jest may come across test suites, but it discreetly disregards the individual tests

Having encountered an issue with Jest testing in a Nuxt/Vue v2 project, I found that after making some changes, the tests were no longer running. The unit tests were either passing or failing initially, but suddenly stopped running altogether. ----------|- ...

Create reactivity in output by utilizing global functions in Vue

I've recently dived into Vue, along with vue-cli and Single File Components. I'm facing a challenge where I need to have a global function that provides formatted text to components throughout my application. This text should be based on the curr ...

Conceal elements and offspring in D3.js through the utilization of JavaScript or jQuery

I am currently customizing a fantastic force directed layout created by @eyaler (http://bl.ocks.org/eyaler/1058611) that offers multiple options. My goal is to conceal a specific node with its children using jQuery or D3 along with JavaScript, not directly ...

Display and conceal button while scrolling in both directions

Seeking assistance with solving a coding challenge. I have created a function that reveals a button (an arrow pointing from bottom to top) when scrolling down. Now, I aim to implement another feature where the button appears after scrolling over 500 pixe ...

Tips for triggering a postback with jquery autocomplete when an option is selected

TEST AREA I've put together a basic demo of jquery-ui autocomplete. QUERY How do I trigger a postback when a selection is made from the autocomplete list? HTML <select id="ddl"></select> <input id="field" type="text"></input& ...

PubSub.js offers a solution for efficiently managing multiple subscriptions or dealing with multiple callbacks in a more streamlined manner

I am currently exploring the most effective approach for handling a specific scenario. My goal is to establish the following flow: 1.) Obtain configuration data from the server (asynchronously) 2.) Execute doStuff() once the configuration data is receive ...

Looping through a PHP foreach function, assigning a distinct identifier for the select element using getElementById

My goal is to extract the price value, $option_value['price'], from a dropdown menu as a string rather than using .value, which fetches something different. I am working with select menus generated in a foreach() loop. Each dropdown menu contain ...

AngularJS: excessive number of event listeners in the view leading to extended loading times

Experiencing an issue with the Angular view when loading the view for the second time. Input: The view loads a list of 1500 items All 1500 items are displayed in a table using ng-repeat with a filter No $watch is used in the view Problem description: ...

Moving information from two modules to the service (Angular 2)

Recently in my Angular2 project, I created two components (users.component and tasks.component) that need to pass data to a service for processing before sending it to the parent component. Code snippet from users.component.ts: Import { Component } fro ...

Step-by-step guide on saving an array to localStorage using AngularJS

Currently working on constructing a shopping cart. My goal is to include the array invoice in localstorage for future reference. I suspect there may be some flaws with this particular approach. angular.module('myApp', ['ngCookies']); ...

Encountering a TypeError in Next.js: "Unable to redefine property: $$id" -

Currently, I am immersed in a Next.js tutorial while following a YouTube guide. The project involves creating a mimic of Facebook Threads to enhance my understanding of Next.js. However, when attempting to create a thread (or a simple post), the applicatio ...

Making an AJAX call to a PHP script to add data

Could you assist me in understanding why my code is resulting in a double insert? I have a JavaScript function that makes an AJAX request to a save.php file to insert data into a database. However, each time I submit it, it performs the insertion twice, al ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

"Enhance your Angular experience with SweetAlert integration using directives and translation

Currently, I am utilizing the Angular implementation of the SweetAlert plugin from GitHub. I am attempting to pass an Angular directive with translation to the title. The variable being passed as the title is: {{ 'register.confirmation_modal.SUPERI ...

Creating a Node.js asynchronous setup function

I'm in the process of transitioning from Nodejs v12 to v14 and I've noticed that v14 no longer waits for the setup function to resolve. My setup involves Nodejs combined with Express. Here's a simplified version of my code: setup().then(cont ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...