I'm using a JS plugin for Checkbox.
This plugin creates a switch button that mimics the state of the checkbox.
When the switch button is toggled its change the checked
value of the checkbox.
<input type="checkbox" v-model="active" class="switch">
<script>
var app = new Vue({
el: '#app',
data: {
active: false
}
})
</script>
However the active
data value is only updated when the user clicks on the checkbox. Changing the checkbox checked
attribute programmatically does not trigger the vue.
How can I update the vue data
when the input is changed programmatically? for instance $("#myinput").prop("checked",true)
Vue updates the v-model
's property whenever the change
* event is triggered. Trigger it:
$("#myinput").prop("checked", true);
$("#myinput")[0].dispatchEvent(new Event('change')); // must trigger NATIVE event
Demo:
new Vue({
el: '#app',
data: {
active: false
}
});
$("#via-jq").click(function() {
let currChecked = $("#myinput").prop("checked");
$("#myinput").prop("checked", !currChecked);
$("#myinput")[0].dispatchEvent(new Event('change'));
})
<script src="https://unpkg.com/vue"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="app">
<input id="myinput" type="checkbox" v-model="active" class="switch"> {{ active }}
</div>
<button id="via-jq">Toggle Via jQ</button>
* This is the case for checkbox
es. The event varies according to input type. E.g. input
event may trigger the update for other types of elements as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With