"Utilizing Vue.js to determine whether a checkbox is filled with data or left

My goal is to create a checkbox using vue js without writing a method. I want the checkbox to default to false, and when checked, I want the data "opening_balance" to be an empty array. Conversely, if the checkbox is unchecked, I want it to be omitted when the data is posted.

For example: POST Unchecked

opening_balance: {}

POST Checked

opening_balance: {date: "2021-08-30", net_total: "1000.00", currency: "USD"}

new Vue({
    el: '#app',
    data() {
        return {
            attributes: {
                opening_balance: {
                    net_total: 0,
                    date: new Date(),
                    currency: USD,
                },
            }
        }
    }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>

<div id="app" style="padding: 1rem;">
<div class="d-flex">
    <input class="form-check-input" type="checkbox" value="false" @click="attributes.opening_balance" v-model="attributes.opening_balance">
    <label class="form-check-label"><b> opening balance</b></label>
</div>
<div v-if="attributes.opening_balance">
    <input type="text" id="Details" class="form-control" v-model="attributes.opening_balance.date">
    <input type="text" class="form-control" v-model="attributes.opening_balance.net_total">
    <input type="text" class="form-control" v-model="attributes.opening_balance.currency">
</div>
</div>

Answer №1

If my understanding is correct, please take a look at the snippet below:

const application = new Vue({
  el: '#app',
  data() {
    return {
      attributes: {
        opening_balance: {
          
        },
      }
    }
  },
  methods: {
    setBalance(e) {
      if(!e.target.checked) {
        this.attributes.opening_balance = {}
      } 
    }
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app" style="padding: 1rem;">
<div class="d-flex">
    <input class="form-check-input" type="checkbox" @click="setBalance">
    <label class="form-check-label"><b> opening balance</b></label>
</div>
<div v-if="attributes.opening_balance">
    <input type="text" id="Details" class="form-control" v-model="attributes.opening_balance.date">
    <input type="text" class="form-control" v-model="attributes.opening_balance.net_total">
    <input type="text" class="form-control" v-model="attributes.opening_balance.currency">
    
    <p>{{ attributes.opening_balance }}</p>
</div>
</div>

Answer №2

To ensure that an empty object is set when the checkbox is unchecked, you can utilize a watcher function.

new Vue({
  el: '#app',
  watch: {
    isPosted: function(val) {
      // Set an empty object when the checkbox is unchecked
      if (!val) {
        this.attributes.opening_balance = {};
      } else {
        this.$set(this.attributes.opening_balance, "date", "2021-08-30");
        this.$set(this.attributes.opening_balance, "net_total", "1000.00");
        this.$set(this.attributes.opening_balance, "currency", "USD");
      }
    },
  },
  data() {
    return {
      isPosted: false,
      attributes: {
        opening_balance: {},
      }
    }
  }
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script>

<div id="app" style="padding: 1rem;">
  <div class="d-flex">
    <input class="form-check-input" type="checkbox" v-model="isPosted">
    <label class="form-check-label"><b> opening balance</b></label>
  </div>
  <div v-if="isPosted">
    <input type="text" id="Detaylari" class="form-control" v-model="attributes.opening_balance.date">
    <input type="text" class="form-control"value v-model="attributes.opening_balance.net_total">
    <input type="text" class="form-control" v-model="attributes.opening_balance.currency">
  </div>
</div>

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

Tips for eliminating double quotes from an input string

I am currently developing an input for a website that will generate a div tag along with its necessary child elements to ensure the website functions correctly. I have a couple of key questions regarding this setup: <!DOCTYPE html> <html> < ...

Learn the process of downloading a pdf file with vuejs and bootstrap-vue

Having trouble uploading a PDF file to my browser and then downloading it afterwards. The upload is fine, but the download isn't working. This is how I am uploading: <b-form-file v-model="form.file" :state="Boolean(form.file)" placeholder="Choose ...

IE 11 encountering issues with Date.parse returning NaN

Whenever I attempt to parse a date in Internet Explorer 11, it throws NaN at me. However, in Chrome and Firefox, I get the timestamp 1494559800000. Date.parse("5/12/2017 09:00 AM") The condition below is where things go wrong for me in IE 11. Is there an ...

Is my Laravel application experiencing caching issues preventing real-time updates?

As I dive into learning AngularJS, I've encountered a strange issue where changes made in my JS files don't always seem to take effect. Even after seeing the GET request to the file in the console, the content remains unchanged. I can delete all ...

What is the process for incorporating items from Slick Grid into a Multi Select TextBox?

Exploring the world of Slick Grid for the first time. Here is where I define my variables in JavaScript. var grid; var printPlugin; var dataView; var data = []; var selectdItems = []; var columns = [ { id: "Id", name: "Id", field: "Id", sortable: t ...

Error message appears when attempting to duplicate vertices in a THREE.Geometry object: 'Vector is not defined'

I am attempting to dynamically add new faces to a mesh, but I keep encountering a console warning: THREE.BufferAttribute.copyVector3sArray(): vector is undefined Despite the warning, this example successfully generates a single triangle that is a repli ...

Tips for running a JavaScript function from a controller in a Rails application

I am looking for a way to upload an image and display it without refreshing the page. One method I am familiar with involves using a hidden iframe and setting the form target to it. Then, I would return a piece of JavaScript from the controller that call ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

Is there a solution to fix the issue with IE causing hover effects not to

I'm currently in the process of designing a website, and I have implemented some image hover effects that reveal elements within the image when you hover over it. These effects are functioning correctly on Chrome, Safari, and Firefox; however, they ar ...

Encountering a problem when trying to utilize material-ui icons in a React application

After installing the Material-UI core and icons packages using npm install @material-ui/core and npm install @material-ui/icons in my React app, I tried to use the FileUploadIcon. Here's how I imported it: import { FileUploadIcon } from '@materia ...

Is it feasible to develop a Grafana datasource plugin that does not rely on an external backend system?

I am in the process of developing a Grafana datasource plugin that operates independently without relying on an external backend. My plugin is based on the simple-json datasource plugin available at: https://github.com/grafana/simple-json-datasource In a ...

Every time an npm installation is attempted, the following error occurs: "npm ERR! Cannot read property 'resolve' of undefined."

Welcome Everyone! Currently, I am facing an issue on my dual boot system where Node and NPM were functioning smoothly on Windows 7. However, now that Windows 7 is not booting up, presumably due to hardware problems, I have resorted to using Windows 10. E ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

Comparison between Microsoft's AJAX Toolkit and jQuery

Ever since the early days of Atlas, our team has relied on Microsoft's AJAX Toolkit for all our web development needs. It wasn't until recently that we stumbled upon the jQuery/Prototype phenomenon and realized what we had been missing out on. Th ...

Three.JS: Utilizing a wireframe material for spheres with the EdgesHelper control

I'm exploring Three.JS for the first time and I have some doubts about whether it's the best tool for my current project. My goal is to create a wireframe material on a simple spherical geometry that looks like this: https://i.sstatic.net/WPfAh ...

The link containing special characters like % cannot access the api

I am facing an issue with retrieving a signUrl from S3. When I make the call with special characters like %, my code does not parse it correctly and I receive a 404 not found error. Here is the ajax request I am using: My API setup: app.get('/websi ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Array of notifications in Vue framework

I am facing an issue with returning an array of notifications from my backend. I have a simple wizard form that displays success messages using Toastification. Here is how it looks: this.$toast({ component: ToastificationContent ...

What is the best way to create an animation for a dynamic menu background image

While hovering over a list item, I want to create an animation where the background image appears to zoom out. $(function () { var image = $('.menu').find('img').attr('src'); $('.menu ul li').mouseover(fun ...

What is the method to display a group label using ng-table?

Does anyone have experience creating a group in ng-table? <div> <div ng-controller="ContractsController" style="position: relative;background:whitesmoke; border:1px solid lightgray; border-radius:5px; margin-top:0px; margin-bottom:5px; h ...