Tips for avoiding passing an empty string when using local storage

I am currently using local storage to transfer two form inputs from a form on page A to a form on page B. The process is working smoothly, but I have encountered an issue. When I navigate directly to page B or visit it without inputting any data on page A, the form fields on page B appear blank. Is there a way to ensure that local storage only passes variables if they exist?

Any assistance would be greatly appreciated!

Below is the code I have implemented so far:

  
    function pageSel() {
      var parseAmount = document.getElementById("stepperAmount").value;
      var parseMonth = document.getElementById("stepperMonth").value;
      localStorage.setItem("amountKey", parseAmount);
      localStorage.setItem("monthKey", parseMonth); 
   }  

Page B.


    function pageSel2() {
        var parseAmount2 = localStorage.getItem("amountKey");
        var parseMonth2 = localStorage.getItem("monthKey");
        document.getElementById("demo1").value = parseAmount2;
        document.getElementById("demo2").value = parseMonth2;
    }

    function roundAmount() {
        var x=document.getElementById("demo1"); 
        x.value=Math.round(x.value/250)*250;
    }

    function roundMonth() {
        var x=document.getElementById("demo2"); 
        x.value=Math.round(x.value/12)*12;
    }

   pageSel2();

Answer №1

To avoid any issues, it is recommended to verify the existence of a value before saving it in localStorage:

function saveData() {
  var amount = document.getElementById("stepperAmount").value;
  var month = document.getElementById("stepperMonth").value;
  if (amount) {
    localStorage.setItem("amountKey", amount);
  }
  if (month) {
    localStorage.setItem("monthKey", month);
  }
}

Answer №2

It seems that the changes I made are not taking effect as expected. Interestingly, when accessing page B directly, the initial values are briefly shown before being replaced by empty data.

Answer №3

In case anyone is facing challenges with this issue, I have devised a solution:

The existing Page A code remains unchanged. However, the new version of Page B is shown below:

function pageSel2() {
        var parseAmount2 = localStorage.getItem("amountKey");
        var parseMonth2 = localStorage.getItem("monthKey");
        document.getElementById("demo1").value = parseAmount2 ? parseAmount: 1000;
        document.getElementById("demo2").value = parseMonth2 ? parseAmount: 36;
    }

    function roundAmount() {
        var x=document.getElementById("demo1"); 
        x.value=Math.round(x.value/250)*250;
    }

    function roundMonth() {
        var x=document.getElementById("demo2"); 
        x.value=Math.round(x.value/12)*12;
    }

   pageSel2();

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

I'm having trouble getting my code to work with axios in Vue.js. How can I fix this issue

I am trying to use axios.get to retrieve data from my database, but I encountered an error. Below is my code in store.js export default new Vuex.Store({ state: { test: null }, mutations: { testt(state, payload) { state.test = payloa ...

Troubleshooting issue with Ajax.Actionlink not canceling request using jQuery's onBegin

In the "onBegin" ajax option of an ajax.actionlink, I have a function that is called. function cancelAction() { $.ajax({ data: { p: "test", z: "value" }, url: '@Url.Action("DoSomething", "TestCtlr")', type: "GET", ...

Tips for dragging and dropping a file attachment directly into your web browser

Google has recently introduced this feature to Gmail, and it doesn't need you to download any additional plugins. This feature is compatible with both Firefox and Chrome browsers, but unfortunately not with Internet Explorer. ...

What can be done to address the issue of v-model select option onchange displaying the previously selected value or becoming stuck on a static value rather than updating

Whenever I navigate to the message page and select a device, the v-model selected value changes. However, if I go to the device or contact page, the v-model selected value remains unchanged or goes back to the last selected value. Below is the function in ...

retaining the scroll position of a window when refreshing a div

There's this issue that's been bothering me lately. I update the database via an ajax call, refresh the div, everything works fine, but it still scrolls to the top of the page. Here's what I have attempted: function postdislike(pid, user, ...

Attempting to discover the secret to keeping a hamburger menu fixed in place once it has been expanded

Exploring this example https:// codepen.io/ducktectiveQuack/pen/mPGMRZ I had trouble understanding the code block, so I resorted to trickery (just remove the space between the '/' and the 'c' lol) My goal is to have the hamburger men ...

Exploring alternatives to setTimeOut() for precise timing of Javascript events, especially when incorporating third party events

Here is the HTML element stack that I am working with: <div class="btn-group btnSortAssType" data-toggle="buttons"> <label class="btn ink-reaction btn-primary active"> <input type="checkbox" value="m">Model </label> ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

A beginner's guide to efficiently indexing tables in AngularJS

Having Trouble with ng-repeat Indexing <tr ng-repeat="Ward in Wardresult "> <td>{{$index + 1}}</td> ...................... some column ....................... </tr> Although, the output ...

Converting a file buffer to upload to Google Cloud Storage

I have been facing an issue while attempting to upload a file to Google Cloud using a buffer and the save function. The problem I am encountering is that even though the files are uploaded to Google Cloud, they are not in the correct format. When I try to ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Having trouble accessing a website that is embedded within an iframe, and experiencing issues with several ajax post requests not functioning properly within the iframe specifically on Chrome

I am currently dealing with a situation where I have two distinct websites, (constructed with PHP) and (also a PHP site). To integrate them, I have embedded site1 inside site2 using an iframe. <iframe src="https://site1.com" seamless width= ...

Customizing material-ui styles within a nested component

I am looking to modify the position of the expandIcon in an ExpansionPanel by changing the right attribute: <ExpansionPanel> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}&g ...

Using Javascript to dynamically copy text to the clipboard

Is there a way to create a function that can automatically copy the current URL in the address bar to the clipboard? Before jumping to conclusions, hear me out: I'm looking for a solution where the copying process happens dynamically, not just when ...

Is there a way to preserve line breaks when programmatically copying text to the clipboard with JavaScript?

Utilizing Javascript alongside a duo of devexpress asp.net controls to dynamically duplicate the contents of an ASPxMemo (multiline textfield) and assign those contents as the body of an email. The copying and pasting is functioning correctly for the most ...

Retrieving a specific time using a JavaScript interface

I am currently implementing a JavaScript control that can be found on this website: My question is, how can I retrieve the selected date from the control in order to pass it to a postback page? I attempted to figure it out myself, but my JavaScript skills ...

Can I obtain a dictionary containing the connections between labels and phrases from the classifier?

I've implemented a LogisticRegressionClassifier using the natural library for node: const natural = require('natural'); const classifier = new natural.LogisticRegressionClassifier(); classifier.addDocument('category1', 'sent ...

Expand the image to fill the entirety of the viewing area

Check out my development website. Whenever you click on an image, a photo slider (using photoswipe) pops up. Is there any way to have the image fill the entire viewport? I attempted using height: 100vh, width: auto, but it didn't work. ...

send the value from the input field to the designated button - link the two buttons

My goal is to create a feature where users can click on a button within the map and open an external page in Google Maps with specific dimensions (500 X 600) and without the Menu bar, Tool bar, or Status bar. // Custom Button Functionality by salahineo ...