Disappear and reappear: the magic of text on page reload with javascript onclick event

I have a JavaScript function that displays text when a button is clicked. The issue I am facing is that the text appears momentarily and then disappears after the page is reloaded.

Below is the paragraph that shows the text once the button is clicked:

<p class="lead" id="class"><strong style="color: red; font-size: 15px; display: none;"></strong></p>

Here is the button in question:

<button type="submit" class="btn btn-primary" onclick="myFunction()">Search</button>

This is the script for my function:

<script>
        function myFunction() {
            document.getElementById("class").innerHTML = "Class current balance total";
        }
</script>

Is there a way to ensure that the text remains visible even after the page reloads?

Note: I am still learning about JavaScript and its functionalities.

Answer №1

The reason for this is due to specifying type="submit". A better option would be to use

<input type="button" ... />
.

Answer №2

That method won't work for achieving what you are trying to do. JavaScript operates differently than that. If you want the data to remain unchanged even after refreshing the page, you'll need to utilize Localstorage.

Localstorage is a key component of JavaScript. By storing the data in the browser's local storage, you can display it again later as needed. Since the value is already stored in the browser, you can easily retrieve and display it whenever required.

Here's how you can implement it: Use localstorage.setItem to save the value, and then use localstorage.getItem to access the saved value and display it on your webpage.

I hope this clarifies things for you!

Answer №3

Utilizing local storage can definitely assist in resolving this issue. I have devised a solution to address your concern. Local storage enables web applications to store data locally within the user's browser, distinguishing it from cookies. In this case, I have stored your text as a key/value pair in local storage. The text is retrieved using the "getItem" method. To view a demonstration of this code, please visit this link

The code example is shown below:

<script>
  //an immediately invoked function that checks if the text is already present in local storage
  (function(){
    //if the text exists in local storage, set the HTML content
    if (localStorage.currentTotal){
    console.log(localStorage.currentTotal);
    document.getElementById('class').innerHTML = localStorage.getItem("currentTotal");
  }
    })();
  
  //function triggered by an onclick event
  function myFunction() {
    // Store data in local storage
    localStorage.setItem("currentTotal", "Class current balance total");
    //set the inner HTML to the value stored in local storage
    document.getElementById("class").innerHTML = localStorage.getItem("currentTotal");

}
</script>

Answer №4

Eliminating the form tag will resolve the issue of the page reloading unnecessarily, allowing it to function properly.

Answer №5

Consider replacing display:none with display:block within your code snippet.

function updateBalance() {
    document.getElementById("element").innerHTML = "Element current balance total";
    document.getElementById("element").children.style.display = 'block';

}

Answer №6

There is an issue with the input value disappearing on refresh, despite attempts to use local storage. However, this can be resolved by implementing the setItem code and getItem functions. Make sure to include window.onload and insert document.getElementById("demo").innerHTML = localStorage.getItem("peanuts"); in your code. By doing so, you will be able to see that the information is stored in localStorage but needs to be retrieved for display. Use f12 to check if it is being stored properly. Additionally, remember to add if(typeof(Storage) !== etc., to your code when working with localStorage.

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

Node does not recognize the $or operator

Currently, I am enrolled in an online course and facing a problem with a query issue. Interestingly, the query functions perfectly fine in the shell, however, when executing the js file, an error arises stating: unknown operator: $or. Here is the crucial c ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

When working with ReactJS and NextJS applications, the variables declared in the .env file may sometimes be received as undefined

In my .env.local file, the following variable is defined: REACT_APP_API_PATH=http://localhost:3600/ The .env.local file can be found at the root level of the project directory. Here is how I am attempting to utilize this variable: console.log('node ...

JavaScript: utilizing JSON, implementing dynamic methods for creatures, and utilizing closures for encaps

Apologies for the unclear title, but I am unsure where the issue lies. Therefore, my task is to create a function that generates JavaScript objects from JSON and for fields that start with an underscore, it should create setters and getters. Here is an e ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

Potential unhandled promise error in react-native

When I use the code below, it produces a "Possible unhandled promise rejection" error: constructor(props){ super(props) DatabaseHandler.getInstance().getItems(function (items) { console.log(items)//successfully print data ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

How does axios .catch() handle JavaScript errors within Redux middleware?

In my React Redux application, I utilize axios as the client for handling AJAX requests. To manage asynchronous actions, I have implemented middleware that performs the following tasks: Detect promise objects Handle resolving the promise with then() in ...

Rendering components asynchronously in ReactJS

After completing my ajax request, I need to render my component. Here is a snippet of the code: var CategoriesSetup = React.createClass({ render: function(){ var rows = []; $.get('http://foobar.io/api/v1/listings/categories/&apo ...

Tips for detecting the backspace key code in an Android browser using JavaScript?

I am faced with a challenge on my HTML JavaScript page... I have implemented a function to handle the keyup event in order to retrieve the key code. Specifically, when the key code is equal to 8 (backspace), a special action should be executed. However, up ...

Implementing dynamic loading of a view partial with CodeIgniter and jQuery

I am currently developing a single page application using CodeIgniter and jQuery. The master page consists of the upper part of HTML including the CSS. <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <met ...

Is there a way to utilize the function body onload in jQuery?

I have some code that needs to be fixed. Currently, when I see <body onload="start()" onresize="resize()" onorientationchange="resize()">, I want the following code snippet to work: $("button").click(function(){ $("body").onload = start; or win ...

An issue occurred while evaluating the Pre-request Script: Unable to access the 'get' property of an undefined object

I need help accessing the response of my POST request in Postman using a Pre-request Script. Script below : var mobiles = postman.environment.get("mobiles"); if (!mobiles) { mobiles =["8824444866","8058506668"]; } var currentMobile = mobiles. ...

Issue with React Router: Trying to access the 'history' property of an undefined object

I am developing a styleguide app that features two dropdown components. Users can select both a brand and a specific component, and the app will display the chosen component styled according to the selected brand. I aim to have these options reflected in t ...

What is the best way to showcase a modal component when the page loads?

Currently, I am working on an HTML5 game page and I am looking to create a modal login form that appears when the user first loads the page. I have attempted to set the state to true and even tried transferring the state to app.js, but unfortunately, neith ...

"Commander.js does not process query strings when used in conjunction with node

I developed a CLI tool using commander.js which has been released on npm. This command-line interface utilizes node-fetch to fetch data from an external API. However, I have received reports from some users stating that the query string in the fetch URL is ...

Pattern matching for ' ... '

I've been struggling to make a regular expression work properly: I need it to match anything that starts with __(' or __(" and ends with ') or ") I attempted using /__\(['"][^']*['"]\)/g and /__\([&apos ...

Guide on Validating and Updating an embedded item within a mongoDB Collection Document

How do I go about updating the values of an embedded object within a mongoDB document? The values displayed for {{service.id}} and {{service.username}} in the table template are correct. However, I am unsure of the correct way to access them within the sa ...

"What could be the reason behind the sudden disappearance of the TinyMCE icon in my Vue

Welcome to my unique website design! https://i.sstatic.net/rtEwF.png Check out the special tinymce code I created https://i.sstatic.net/8su0i.png https://i.sstatic.net/9y2AO.png ...

Transferring retrieved information from one division to another

This snippet of code demonstrates the process of fetching names from a MySQL database using PHP and Ajax. Updated Code index.php <html> <head> <script language="javascript"> function showresult( ...