Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define values for checked and unchecked checkbox with VUE.js?

Tags:

vue.js

Is there a way how define checked and unchecked value for .? Now VUE sets model to true/false which makes sense but in real apps data format is somethink like '1' => true and ''=>false. How to achive this in VUE?

like image 778
David Marko Avatar asked Aug 20 '15 13:08

David Marko


People also ask

How do you send a value for a checkbox when it is unchecked?

If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value , generated by JavaScript perhaps.

How do you check checkbox is checked or not in VUE JS?

To watch for checkbox clicks in Vue. js, we can listen to the change event. to add the @change directive to the checkbox input to listen to the change event. Then we can get the checked value of the checkbox with e.

How do you check and uncheck a checkbox?

Once the checkbox is selected, we are calling prop() function as prop( "checked", true ) to check the checkbox and prop( "checked", false ) to uncheck the checkbox.

How do I check a checkbox in Vue?

Vue Set Checkbox as Checked To do this, we need to bind the checkbox value with the v-model directive. This can be done by applying simple logic, and that is. Set the checkbox value to true, so if the value is truthy, then the initial state will be checked.


2 Answers

You can use true-value and false-value:

https://vuejs.org/v2/guide/forms.html#Checkbox-1

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

// when checked:
vm.toggle === 'yes'
// when unchecked:
vm.toggle === 'no'
like image 85
Sphinxxx Avatar answered Sep 27 '22 22:09

Sphinxxx


Not sure what it is exactly you need, but, as you say, if you do:

{{ boxtest }}

<input type="checkbox" v-model="boxtest"/>

Boxtest will display as 'true' or 'false' as you check or uncheck the box.

If you do need to convert it you could just do the likes of:

{{ boxtest ? 1 : '' }}
like image 37
thesunneversets Avatar answered Sep 27 '22 22:09

thesunneversets