Saving user input as a local variable to be utilized on a different web page

I am attempting to capture a user input from a form and then utilize that variable on a separate page. This process should be straightforward, but I am not receiving any results and I am unsure of the reason why.

Here is the code on the first page:

<div class="container-fluid d-flex justify-content-center" id="mySearchBar">

        <div class="row d-flex justify-content-center ">


            <h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>

            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar ">
               <script> localStorage.setItem('loan', document.getElementById("searchbar").value );</script>
                <div class="input-group-append">
                    <button class="btn btn-secondary" id='searchButton' type="submit">
                    <i class="fa fa-search"></i>
                  </button>
                </div>

            </div>

Next, on the second page, I have the following:

<script>
           var loan = localStorage.getItem('searchbar');
           console.log(loan);
           </script>

Any assistance would be greatly appreciated!

Answer №1

To retrieve a value entered by the user, it is essential to do so after they input the value. An event listener should be used to fetch and retain the value. For your specific scenario, it would be most effective to enclose your inputs within a <form> tag and monitor the form submission. This approach enables capturing the click of the submit button and/or the pressing of the enter key on the input field.

Given that you are utilizing Bootstrap-4, it is assumed that you have jQuery imported.

<form class="container-fluid d-flex justify-content-center" id="mySearchBar">
  <div class="row d-flex justify-content-center ">
    <h3 class="heading text-center pt-5">Search the Title Below and Find The Site It's Hosted On!</h3>
    <div class="input-group">
      <input type="text" class="form-control" placeholder="Search this blog" id="searchbar" name="searchbar">
      <div class="input-group-append">
        <button class="btn btn-secondary" id='searchButton' type="submit">
          <i class="fa fa-search"></i>
        </button>
      </div>
    </div>
  </div>
</form>

<script>
  // utilize a constant key string on both pages
  const searchbar_local_storage_key = 'my_unique_key_for_searchbar_value'

  // for the page where the stored value needs to be fetched
  $(document).ready(function() {
    let stored_value = localStorage.getItem(searchbar_local_storage_key)
    console.log('searchbar localStorage value at document.ready:')
    console.log(stored_value)
  })

  // for the page where the value needs to be stored/updated
  $(document).ready(function() {
    let $searchbar = $('#searchbar')
    console.log('searchbar input value at document.ready:')
    console.log($searchbar.val())

    $('#mySearchBar').on('submit', function(event) {
      console.log('searchbar form submitted')
      // prevent form submission if necessary
      event.preventDefault()
      
      // retrieve the current value
      let term = $searchbar.val()
      console.log('searchbar input value at form.submit:')
      console.log($searchbar.val())

      // store values
      localStorage.setItem(searchbar_local_storage_key, $searchbar.val());
      console.log('new searchbar value in localStorage:')
      console.log(localStorage.getItem(searchbar_local_storage_key))

    })
  })
  
</script>

Observe the demonstration here https://jsfiddle.net/chan_omega/qt510oms/
Enter a value, submit, review the output in the console, then refresh the page (to mimic a different page). You will notice the identical value loaded from 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

Choose an image and save the selection information for the following page (Tarot card)

I'm in the process of creating a website that showcases multiple tarot cards. The goal is for users to select the cards they're interested in and have their chosen card displayed on the next page. I've implemented some code for selecting the ...

Encountering the error message "Uncaught Error: [vuex] Getters must be functions, but 'getters.getters' is {}. This occurred while splitting the Vuex store into modules in Vue.js."

As a beginner in VUEX, I am experimenting with building a test application to dive deeper into the world of VUEX. I have organized my VUEX store into modules, where each module has its own getter.js file. Getters, actions, and mutations are imported into i ...

Unleashing the power of TypeScript with Solid JS Abstract Class

Why am I getting an undefined error for my calcUtilisation method when using an Abstract Class as the type in createStore? Is there a way to utilize a type for the data along with a method within the same class for createStore? abstract class Account { ...

Full-screen modal fade not functioning properly

I am trying to implement multiple fullscreen modals on a single page, but I am facing an issue where they slide in and out at an angle instead of just fading in and out. I have been unable to achieve the desired effect of a simple fade transition. If you ...

Error: Disappearing textarea textContent in HTML/TS occurs when creating a new textarea or clicking a button

I've encountered an issue with my HTML page that consists of several textareas. I have a function in place to dynamically add additional textareas using document.getElementById("textAreas").innerHTML += '<textarea class="textArea"></text ...

Having trouble getting event modifiers to work in Vue when added programmatically

Trying to dynamically add events using v-on through passing an object with event names as keys and handlers as values. It appears that this method does not support or recognize event modifiers such as: v-on=“{‘keydown.enter.prevent’: handler}” T ...

Node.js application experiences a delay when calling Mongoose Model.save()

I've been delving into the realms of node and mongo in order to construct a basic web application while also expanding my knowledge on web development. However, I'm encountering an issue when it comes to calling Model.save(); the continuation fun ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Breadcrumb navigation that is determined by data hierarchies and relationships between parent and child items

I am looking to implement a dynamic breadcrumb system on my website using data-driven methodology. The necessary data is stored in a MariaDB database and has the following structure: parent_id | parent_name | child_id | child_name ——————— ...

Shuffling images in JavaScript using z-index for a dynamic deck effect

My current code stack images like a deck of cards with changing z-Index values to create an animation. However, I am looking to make the animation reverse as well and not just go forward in a linear manner. I'm seeking ideas on how to achieve this wit ...

stepper vue with previous and next buttons

I am trying to create previous and next buttons in Vue, but I am struggling a bit because I am new to learning Vue. I have some methods like this.activeIndex < this.activeIndex - 1 that I need to implement. Can someone help me with how to do this? cons ...

Is it feasible to decrease the lateral margins of Bootstrap's container without the need for custom CSS? If so, what is the method?

My web page includes several screenshots to illustrate the issue I am facing. One of my challenges is the scroll bar below the table, which I find displeasing. In an attempt to resolve this, I decided to adjust the lateral margins slightly. Here's a s ...

Update the JavaScript and CSS files following an AJAX request with $.get

I am encountering an issue where my global CSS and JS files contain all the necessary definitions, but when I load new HTML blocks via AJAX $.get, these new elements do not receive the correct CSS/JS definitions. Is there a convenient way to refresh the ...

Securing string parameters in Django templates for JavaScript function usage

Can anyone help me with a JavaScript function that is returning a set of objects? return Func("{{id}}", "{{name}}") I'm encountering an issue when passing strings that contain quotes, such as "Dr.Seuss' "ABC""BOOk"", which leads to invalid synt ...

Is it the same item in one situation, but a completely different item in another?

I am currently investigating the behavior of objects in JavaScript, particularly when it comes to copying one object onto another. It seems that sometimes they behave as if they are the same object, where modifying one also modifies the other. Many resourc ...

Error message: "No elements were found in Ember.js jQuery cycle slideshow"

As I transition a traditional HTML site to an Ember.js application, I encountered a problem with the jQuery Cycle slideshow plugin. With approximately 10 slideshows on the site, I aimed to create a reusable partial to pass data to. Although the data passi ...

Tips for preventing the ng-click event of a table row from being triggered when you specifically want to activate the ng-click event of a checkbox

So, I've got this situation where when clicking on a Table Row, it opens a modal thanks to ng-click. <tr ng-repeat="cpPortfolioItem in cpPortfolioTitles" ng-click="viewIndividualDetailsByTitle(cpPortfolioItem)"> But now, there&apos ...

Combining NodeJS with Javascript for wrangler bundling: A guide

The challenge: My goal is to create a Cloudflare worker that utilizes NodeJS dependencies. Unfortunately, I'm facing obstacles with Wrangler, preventing me from deploying it using the command wrangler deploy. The obstacle: X [ERROR] Could not resolve ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...