Vue 2 Set, Get & Submit Multiple Checkboxes Values with REST API

Vue js checkbox tutorial; In this detailed guide, we will show you how to get values from multiple checkboxes and store them into the server in the vue js application using the Axios package.

Also, we will show you how to make post requests using REST API to send the multiple checkbox values to the server; as far as rest API is concerned, we will use the test server using the JSON server package and consume the REST API using Axios library in vue.

We will use the profound v-model directive to enable the two-way communication in the checkbox element; the v-model invokes the two-way data-binding that can be applied to the input, select, and textarea HTML elements.

It automatically figures out the eloquent way that conventionally updates the element based on the input type. However, the v-model scorns the initial value, checked, or selected attributes detected on any form elements.

Here is a bit more about the v-model directive; it manages various properties and emits different events for several input elements:

  • text and textarea elements use value property and input event.
  • checkboxes and radio buttons use checked property and change event.
  • select fields use value as a prop and change as an event.

Handle Multiple Checkboxes Values in Vue

  • Step 1: Setup Vue Environment
  • Step 2: Install Vue Js Application
  • Step 3: Add Bootstrap
  • Step 4: Install Axios Package
  • Step 5: Create Multi Checkbox Component
  • Step 6: Set Up JSON Server Backend
  • Step 7: Handle Multiple Checkboxes Values in Vue
  • Step 8: Start Vue Project

Setup Vue Environment

Make sure to install VUE cli on your development system.

npm install -g @vue/cli

# or

yarn global add @vue/cli

Install Vue Js Application

In this step, execute the command to begin installing a new vue app, avoid if the app is already created.

vue create vue-galactic-app

Move towards the project.

cd vue-galactic-app

Vue Gatsby Error

Node.js Gatsby error – “digital envelope routines::unsupported …”

Error: digital envelope routines::unsupported

opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

To remove above error for invoking the app, make sure to update the "scripts": [] array in package.json file.

"scripts": {
    "serve": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service serve",
    "build": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service build",
    "lint": "export NODE_OPTIONS=--openssl-legacy-provider && vue-cli-service lint"
},

Fix Multi Word Error

In order to fix multi-word error, insert the given code in vue.config.js file.

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
})

Add Bootstrap

Run command to install the Bootstrap CSS framework in the Vue app, and it allows creating eloquent UI components; however, this step is optional.

npm install bootstrap

Install Axios Package

Next, install the Axios library in the vue app; it gives the agile HTTP methods to communicate with the server.

npm install vue-axios axios

Next, register the VueAxios, axios and bootstrap packages in the main src/main.js configuration file.

import Vue from 'vue'
import App from './App.vue'

import VueAxios from 'vue-axios'
import axios from 'axios'


Vue.use(VueAxios, axios)
import 'bootstrap/dist/css/bootstrap.min.css';


new Vue({
  render: h => h(App)
}).$mount('#app')

Create Multi Checkbox Component

Further, get into the src/components folder, create MultiCheck.vue file and define the mentioned code to set up the vue template.

<template>

</template>
 
<script>

export default {
  name: "App",
  data() {
    return {
    };
  }
};
</script>

Next, globally register the newly built component in the src/App.vue file, this way, is accessible in all the subcomponents of our main vue root instance.

<template>
  <div class="container mt-4 text-center">
    <MultiCheck />
  </div>
</template>

<script>
import MultiCheck from './components/MultiCheck.vue'

export default {
  name: 'App',
  components: {
    MultiCheck
  }
}
</script>

Set Up JSON Server Backend

In this section, you will learn how to create a fake server to build REST APIs to store multiple checkboxes values; if you have an actual API, then use it; otherwise, get along and follow the instruction to set up a test server.

npm install json-server

Create backend folder in the project root, also create db.json file after which add the code in backend/db.json file.

{
    "users": [{
        "id": 1,
        "subjects": []
    }]
}

Let’s start the backend server on a specific port, and you may change the port number if you want.

json-server --watch backend/db.json --port 8888

Handle Multiple Checkboxes Values in Vue

The form component is holding the 4 checkboxes; each contains a v-model=”” directive; this tag evokes the two-way data binding, the checkboxes values are stored on the database when a user checks any of the checkboxes values.

The onSubmit() method sending the checkboxes values t the server with the help of Axios and rest API.

Open and update given code in components/MultiCheck.vue file.

<template>
  <div>
    
    <h2>Vue Multiple Checkbox Demo</h2>

    <form @submit.prevent="onSubmit()">
      <div class="form-group">

        <div class="form-check">
          <label for="mathematics" class="form-check-label">
            <input type="checkbox" 
                class="form-check-input"
                id="mathematics" 
                value="mathematics" 
                v-model="subjects" />Mathematics
          </label>
        </div>

       <div class="form-check">
          <label for="science" class="form-check-label">
            <input type="checkbox" 
                class="form-check-input"
                id="science" 
                value="science" 
                v-model="subjects" />Science
          </label>
        </div>

        <div class="form-check">
          <label for="english" class="form-check-label">
            <input type="checkbox" 
                class="form-check-input"
                id="english" 
                value="english" 
                v-model="subjects">English
          </label>
        </div>

        <div class="form-check">
          <label for="history" class="form-check-label">
            <input type="checkbox" 
                class="form-check-input"
                id="history" 
                value="history" 
                v-model="subjects">History
          </label>
        </div>
      </div>

      <div class="form-group">
        <button class="btn btn-primary">Submit</button>
      </div>
    </form>
  </div>
</template>

<script>

export default {
  name: "App",
  data() {
    return {
      subjects: []
    }
  },
  methods: {
    onSubmit() {
      let userObjec = {
        subjects: this.subjects
      }
      this.axios.post(' http://localhost:8888/users', userObjec)
          .then(response => console.log(response.data));
    }
  }
}
</script>

Start Vue Project

In the last section, start the vue app by invoking the vue development server.

npm run serve
http://localhost:8080

Vue Multiple Checkboxes Values

Conclusion

In this vue js checkboxes tutorial, we addressed how to create a form with multiple checkboxes similarly to get values of checkboxes and use the HTTP post request to send the checkboxes values to the server.

Apart from checkboxes, we learned how to create a testing REST API using the JSON server and use the Axios package to consume the REST API. Thus, this Vue multiple checkbox tutorial, with the example, ends here.