0

I have this checkbox

<div class="form-check form-check-inline col-lg-2">
  <input v-model="propertyData.fitness_centre" type="checkbox" class="form-check-input" id="dc_li_u" />
  <label class="form-check-label" for="dc_li_u">Fitness Centre</label>
</div>

and i am saving the state in a database so when editing the state is restored and displays whether the checkbox was checked or not.

However, i need the checkbox to have a string value that is saved to the database when the checkbox is clicked such that when a checkbox has a string value, its checked and when the string value is empty the checkbox is not checked.

I have many checkboxes and so, i wanted the entire logic to be contained inside the checkbox. How can i modify the checkbox to do this?

2 Answers 2

1

You can use true-value and false-value attributes, to assign specific values when checking/unchecking.

new Vue({
  el: "#app",
  data: {
      fitness_centre: "true value"
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class="form-check form-check-inline col-lg-2">
    <input v-model="fitness_centre" true-value="true value" false-value="" type="checkbox" class="form-check-input" id="dc_li_u" />
    <label class="form-check-label" for="dc_li_u">Fitness Centre</label>
    <div>Value: {{ fitness_centre }}</div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, much simpler than mine
1

You could use a change-event handler to set propertyData.fitness_centre to the desired value based on the checked state. Also bind <input>.checked to propertyData.fitness_centre so that the checked state is bound to the model's truthiness (empty string is false, otherwise true).

<template>
  <input type="checkbox"
         @change="onChange"
         :checked="propertyData.fitness_centre"
         value="fitness_centre">
</template>

<script>
export default {
  data() {
    return {
      propertyData: { fitness_centre: '' }
    }
  },
  methods: {
    onChange(e) {
      this.propertyData.fitness_centre = e.target.checked ? e.target.value : ''
    }
  }
}
</script>

demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.