Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved in local storage; if later false is selected, the true value will be deleted and false will be saved instead. The same process should work vice versa. I hope this explanation makes sense.

You can view my code on codesandbox

<template>
  <div>
    <div>
      <label
        >One
        <input type="radio" name="radio" value="true" v-model="websiteAccept" />
      </label>
      <label
        >No
        <input
          type="radio"
          name="radio"
          value="false"
          v-model="websiteAccept"
        />
      </label>
      <p>{{ websiteAccept }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      websiteAccept: null,
    };
  },
};
</script>

Answer №1

To store the value of websiteAccept in local storage whenever it changes, you can add a watcher.

Here is an example:

data() {
  return {
    websiteAccept: null,
  };
},
watch: {
  websiteAccept(value) {
    this.saveToLocalStorage(value);
  },
},
methods: {
  saveToLocalStorage(value) {
    localStorage.setItem("websiteAccept", value);
  },
}

Check out the updated sandbox here:

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

Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading: <div id="customerdetailsDIV" class="well main-well clearfix"> @Html.Partial("_customer_details", Mod ...

Error: Unable to access property 'nTr' as it is not defined

When I invoke the fnSelect function, an error occurs in Chrome: Uncaught TypeError: Cannot read property 'nTr' of undefined This is the code snippet causing the issue: $('#ToolTables_table_id_0, #ToolTables_table_id_1').mousedown(fun ...

Python sends back a list containing garbled characters to Ajax

Need help fixing the output of a Python list returned to Ajax, as it appears strange. ap.py @app.route('/_get_comUpdate/', methods=['POST']) def _get_comUpdate(): comNr = request.form.get('comNr') com_result ...

What is the best way to break down this function from props in React?

Forgive me if this question sounds naive, but as I delve into the world of React and useState, I am encountering a scenario where I have a signup function coded. Upon sending a username and password through a POST request to an API endpoint, a response mes ...

Retrieve information on input type hidden using Vue.js

Every time I attempt to retrieve the data "Id" from my list, the script returns the wrong Id. I specifically need the Id from that field, but the value returned is incorrect. <input type="hidden" name="Id" id="Id" v-mode="todo.Id"> I have resorte ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

JavaScript HTML content manipulation

Why doesn't this code work? innerHTML cannot handle something so complex? <html> <head> <script type="text/javascript"> function addTable() { var html = "<table><tr><td><label for="na ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Experimenting with Vue.js filters and QA testing techniques

Upon creating a sample project using vue-cli with the command vue init webpack my-test3, I decided to include both e2e and unit tests. Question 1: Following the documentation for template filters, I attempted to add a new filter in main.js: import Vue fro ...

Is there a way to verify the presence of months in a column related to departments?

Is there a way to validate whether the current row aligns with the current column month and year? If not, can it be set to 0. Let's consider the current dataset. Presenting my resultData https://pastebin.com/GHY2azzF I want to verify if this data ...

Element dynamically targeted

Here is the jQuery code I currently have: $('.class-name').each(function() { $(this).parent().prepend(this); }); While this code successfully targets .class-name elements on page load, I am looking to extend its functionality to also target ...

Enhance click functionality on list item content using knockoutjs

Check out my app on GitHub or view it live at this link. I'm trying to implement a feature where clicking on each item, like "Bookworm Buddy," will toggle its description within the project. Here's what I've attempted so far: function AppV ...

Retrieve data from the api

Can someone provide the JavaScript code to loop through an API, extract the coordinates/address, and map it? Here is a simple demonstration of fetching the API data: const fetch = require("node-fetch"); fetch('url').then(function (resp ...

Employ Javascript to display a list of all messages sent through Twilio

I'm referencing the Twilio Node.js documentation available at: My goal is to display a list of all messages in the message log for an account. I'm following this example: var accountSid = 'your_sid'; var authToken = "your_auth_token ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

Vertically animating an image using jQuery

I have been experimenting with trying to make an image appear as if it is floating by using jQuery to animate it vertically. After some research, I stumbled upon this thread: Animating a div up and down repeatedly which seems to have the solution I need. H ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...

import an external JavaScript file in an HTML document

Looking to load a .js file from a simple HTML file? If you have these files in the same folder: start.js var http = require('http'); var fs = require('fs'); http.createServer(function (req, response) { fs.readFile('index.htm ...