Table of Contents
Checkbox example
Example
Using local storage in JavaScript
Check LocalStorage browser compatibility
Used localStorage method
1. setItem()
2. GetItem()
3. DeleteItem()
4. clear()
page2.html
Home Web Front-end JS Tutorial Show selected checkbox on another page using JavaScript?

Show selected checkbox on another page using JavaScript?

Sep 13, 2023 am 11:09 AM

使用 JavaScript 在另一个页面上显示选定的复选框?

In this article, you will learn how to get all checkboxes on other pages using JavaScript. A checkbox is a selection type, a binary selection type that is true or false. It is an option in the form of GUI presented on the page, with which we can get more input from the user. True if a box is checked, which means the user has selected the value; if it is unchecked, it means the user has not selected the value.

The difference between checkboxes and radio buttons is that when using radio buttons, the user can only select one value, while when using checkboxes, the user will be able to select multiple values.

Checkbox example

<html>
<body>
   <input type="checkbox" value="false" onchange="alert('checked')"/>Example of checkbox <br/>
</body>
</html>
Copy after login

From the above output, you can observe that the box is checked, which indicates that the user has selected the value.

The JSON.parse() method always takes arguments in string format (i.e. we must surround the value with single quotes).

Example

Let’s look at a program example:

<html>
<body>
   <form>
      <h1>Print checked button values.</h1> <hr/>
      <big>Select your favourite fruits: </big><br />
      <input type="checkbox" name="inputCheck" value="Apple" />Apple<br />
      <input type="checkbox" name="inputCheck" value="Mango" />Mango<br />
      <input type="checkbox" name="inputCheck" value="Banana" />Banana<br />
      <input type="checkbox" name="inputCheck" value="Orange" />Orange<br />
      <p>
         <input type="submit" id="submitBtn" value="submit" onclick="printChecked()"/>
      </p>
   </form>
   <script type="text/javascript">
      function printChecked() {
         var items = document.getElementsByName("inputCheck");
         var selectedItems = "";
         for (var i = 0; i < items.length; i++) {
            if (items[i].type == "checkbox" && items[i].checked == true){
               selectedItems+=items[i].value+"";
            }
         }
         alert(selectedItems);
      }
   </script>
</body>
</html>
Copy after login

From the output, you can observe that we are printing the selected checkboxes specified by the alert message on the same page. Before that, let's first understand the concept of local storage.

Using local storage in JavaScript

LocalSorage is a type of data storage in web browsers. Data can be stored using this website and the data will always remain in storage and will not disappear when you close your browser.

Another option is cookies, which are also used to store site data. This storage limit is approx. 2Mb in the browser, while localStorage comes with 5Mb storage, which is larger in terms of cookie storage size

In order to use localStorage effectively and safely, users should remember some terms.

  • is not secure in storing sensitive data such as passwords and other information that users should not share publicly.

  • Is the data stored in the browser itself rather than on the server? And its operations are synchronous, that is, one operation after another is processed sequentially.

  • It has a larger storage data capacity compared to the cookie storage size.

  • Almost all modern browsers support it and are compatible with the latest versions.

Check LocalStorage browser compatibility

To check if your browser supports localStorage, execute the following code in the browser console. If it is not defined, it means your browser supports localStorage.

Example

<html>
<body>
   <script type="text/javascript">
      if (typeof(Storage) !== "undefined") {
         document.write("Your browser support localStorage.")
      } 
      else {
         document.write("Your browser doesn't support localStorage.")
      }
   </script>
</body>
</html>
Copy after login

Used localStorage method

1. setItem()

This method is used to add data to storage. We pass the key and value to this method to add data.

localStorage.setItem("name", "Kalyan");
Copy after login

2. GetItem()

This method is used to get or retrieve data present in the storage. We pass the key into this method to get the value associated with that key.

localStorage.getItem("name");
Copy after login

3. DeleteItem()

This method is used to delete specific data present in the storage. We pass the key to this method and it deletes the key-value pairs that exist as data in the storage.

localStorage.removeItem("name");
Copy after login

4. clear()

This method is used to clear the local storage data existing in the storage.

localStorage.clear();
Copy after login

Tip: To check the size of localStorage, you can execute the following syntax in the browser console

console.log(localStorage.length);
Copy after login

Let's send this value to another page. We will first add all selected checked values ​​to the local storage using setItem() and then on the next page we will get the values ​​out using the getItem() method.

Our JavaScript function that adds value to local storage will be

<script type="text/javascript">
   function printChecked() {
      var items = document.getElementsByName("inputCheck");
      var arr=[];
      for (var i = 0; i < items.length; i++) {
         if (items[i].type == "checkbox" && items[i].checked == true){
            arr.push(items[i].value);
         }
      }
      localStorage.setItem("ddvalue", arr);
      return true;
   }
</script>
Copy after login

Here, get all checkbox items in the items variable, and in the arr array, we will add all items that have been marked true, indicating that the user has selected them. and add the array to local storage.

JavaScript function to retrieve the value from the storage on the second page

<script>
   var arr=localStorage.getItem("ddvalue");
   var selectedItems = "";
   for (var i = 0; i < arr.length; i++) {
      selectedItems += arr[i] + ", ";
   }
   document.getElementById("result").innerHTML= selectedItems;
</script>
Copy after login

The array arr here stores the values ​​retrieved from storage along with the key values. We will take an empty string variable named selected item and then append all array items. Finally, we will print the id result in its place.

page1.html

<html>
<body>
   <form action="page2.html">
      <h1>Page1</h1> <hr/>
      <big>Select your favourite fruits: </big><br />
      <input type="checkbox" name="inputCheck" value="Apple" />Apple<br />
      <input type="checkbox" name="inputCheck" value="Mango" />Mango<br />
      <input type="checkbox" name="inputCheck" value="Banana" />Banana<br />
      <input type="checkbox" name="inputCheck" value="Orange" />Orange<br />
      <p><input type="submit" id="submitBtn" value="submit" onclick="printChecked()"/></p>
   </form>
   <script type="text/javascript">
      function printChecked() {
         var items = document.getElementsByName("inputCheck");
         var arr=[];
         for (var i = 0; i < items.length; i++) {
            if (items[i].type == "checkbox" && items[i].checked == true){
               arr.push(items[i].value);
            }
         }
         localStorage.setItem("ddvalue", arr);
         document.write("Submitted Successfully. <br> To see the result, please run the Page2.html")
         return true;
      }
   </script>
</body>
</html>
Copy after login

page2.html

<html>
<head>
   <title>Print checked button values on another page- JavaScript.</title>
</head>
<body>
   <h1>Page2</h1>
   <hr/>
   The Selected course is: <b><span id="result"></span></b>
   <script>
      var arr=localStorage.getItem("ddvalue");
      arr=arr.split(",");
      var selectedItems = "";
      for (var i = 0; i < arr.length; i++) {
         selectedItems += "<br>" + arr[i] ;
      }
      document.getElementById("result").innerHTML= selectedItems;
   </script>
</body>
</html>
Copy after login

From the output you can observe that on the first page page1.html all the items are displayed and when the user selects an item from the selected list it adds all the selected values ​​to the storage with the key name for value. When the user presses the submit button, it redirects him to the next page i.e. page2.html. On page 2, the program will fetch the user-selected value from storage using the key value and loop through the array, appending and printing the final value.

The above is the detailed content of Show selected checkbox on another page using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles