Reputation: 2408
I just want to determine whether a checkbox is checked or not in Vue js 2. In jquery we have functions like $('input[type=checkbox]').prop('checked'); which will return true if checkbox is checked or not. What is the equivalent function in Vue js.
Here is the scenario with code. Please note i am using laravel with its blade templates.
@foreach ($roles as $role)
<input type="checkbox" v-on:click="samplefunction({{$role->id}})" v-model="rolesSelected" value="{{$role->id}}">
@endforeach
The js part is
<script>
var app = new Vue({
el: '#app1',
data: {
rolesSelected:"",
},
methods : {
samplefunction : function(value) {
// Here i want to determine whether this checkbox is checked or not
}
},
});
</script>
Upvotes: 34
Views: 68354
Reputation: 25
Use the event handler change
instead of click
and add a second argument $event
into your function call like:
<input type="checkbox" v-on:change="samplefunction({{$role->id}}, $event)" v-model="rolesSelected" value="{{$role->id}}">
In your methods, use the second argument and check with event.target.checked
if your checkbox is true
or false
, clicked or not clicked
var app = new Vue({
el: '#app1',
data: {
rolesSelected:"",
},
methods : {
samplefunction : function(value, event) {
if(event.target.checked) {
console.log('The checkbox is clicked')
}
}
},
});
Upvotes: 1
Reputation: 32354
You can do something like:
if(this.rolesSelected != "") {
alert('isSelected');
}
or
v-on:click="samplefunction({{$role->id}},$event)"
samplefunction : function(value,event) {
if (event.target.checked) {
alert('isSelected');
}
}
Upvotes: 61
Reputation: 415
This worked for me.
<input type="checkbox" :id="poid" class="unchecked" name="single_select" ref="rolesSelected">
function (){
if(this.$refs.rolesSelected.checked == false) {
//do something
}
}
function (){
if(this.$refs.rolesSelected.checked == true) {
//do something
}
}
Upvotes: 10