Vue Js post checkbox data to API:To post checkbox data from a Vue.js application to an API, you can follow these steps. First, create a checkbox input element and bind its value to a data property in your Vue instance. Next, create a method that gets triggered when the form is submitted. Inside this method, use the axios
library to make a POST request to your API endpoint, sending the checkbox data as part of the request payload. Finally, handle the response from the API as desired. Remember to include the necessary headers and API endpoint configuration to ensure a successful request and response.
How can I use Vuejs to send checkbox data to an API?
This Vuejs code creates a form with checkboxes representing a list of rivers. When a checkbox is checked or unchecked, the handleCheckboxChange
method is called to update the selectedRivers
array accordingly. When the form is submitted, the handleSubmit
method is called, which prevents the default form submission behavior, sends a POST request to an API endpoint (specified as /your-api-endpoint
), and includes the se
Vue Js post checkbox data to API Example
<div id="app">
<div class="container">
<h3>Vue js post checkbox data to API</h3>
<form @submit="handleSubmit">
<div v-for="river in rivers" :key="river.id">
<label>
<input
type="checkbox"
:value="river.name"
:checked="selectedRivers.includes(river.name)"
@change="handleCheckboxChange"
/>
{{ river.name }}
</label>
</div>
<button type="submit">Submit</button>
</form>
</div>
</div>
<script type="module">
const app = Vue.createApp({
data() {
return {
selectedRivers: [],
rivers: [
{ id: 1, name: "Ganga" },
{ id: 2, name: "Yamuna" },
// Add more rivers as needed
],
};
},
methods: {
handleCheckboxChange(event) {
const { value, checked } = event.target;
if (checked) {
this.selectedRivers.push(value);
} else {
this.selectedRivers = this.selectedRivers.filter(
(river) => river !== value
);
}
},
handleSubmit(event) {
event.preventDefault();
// Perform your post request with the selectedRivers data
axios
.post("/your-api-endpoint", {
selectedRivers: this.selectedRivers,
})
.then((response) => {
console.log(response.data);
alert("successfully submitttedF");
})
.catch((error) => {
console.error(error);
});
},
},
});
app.mount("#app");
</script>