Home  >  Article  >  Web Front-end  >  Show selected checkbox on another page using JavaScript?

Show selected checkbox on another page using JavaScript?

WBOY
WBOYforward
2023-09-13 11:09:08713browse

使用 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>

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>

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>

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");

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");

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");

4. clear()

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

localStorage.clear();

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

console.log(localStorage.length);

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>

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>

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>

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>

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:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete