I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.
Example:
<ul class="object administrator-checkbox-list">
<li v-for="module in modules">
<label v-bind:for="module.id">
<input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id">
<span>#{{ module.name }}</span>
</label>
</li>
</ul>
An example of the modules data:
[
{
"id": 1,
"name": "Business",
"checked": true
},
{
"id": 2,
"name": "Business 2",
"checked": false
},
]
What can I do to initially set the checked status of the checkboxes?
To set the state of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.
The following code will bind the checkbox to that property:
<input type="checkbox" v-model="module.checked" v-bind:id="module.id">
If you'd like to know more about how v-model works in this situation, here's a link to the documentation about Form Input Binding.
Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the v-bind:checked="booleanValue" or the shorter way :checked="booleanValue", for example:
<input
id="checkbox"
type="checkbox"
:value="checkboxVal"
:checked="booleanValue"
v-on:input="checkboxVal = $event.target.value"
/>
That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).
In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
I had similar requirements but I didn't want to use v-model to have the state in the parent component. Then I got this to work:
<input
type="checkbox"
:checked="checked"
#input="checked = $event.target.checked"
/>
To pass down the value from the parent, I made a small change on this and it works.
<input
type="checkbox"
:checked="aPropFrom"
#input="$emit('update:aPropFrom', $event.target.checked)"
/>
I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented native events from occurring with:
<input type="checkbox" #click.prevent="toggleConfirmedStatus(render.uuid)"
:checked="confirmed.indexOf(render.uuid) > -1"
:value="render.uuid"
/>
removing the .prevent from the #click handler fixed my issue.
<input v-if = "module.checked == true" checked type="checkbox" >
<input v-else-if = "module.checked == false" type="checkbox" >
I have solved this with use of v-if and v-else-if
I use both hidden and checkbox type input to ensure either 0 or 1 submitted to the form. Make sure the field name are the same so only one input will be sent to the server.
<input type="hidden" :name="fieldName" value="0">
<input type="checkbox" :name="fieldName" value="1" :checked="checked">
In my case I had an simple boolean type, so What I did is:
in my html:
<input type="checkbox" :checked="article.is_public" :value="article.is_public" #change="updateIsPublic($event.target.checked)">
methods: {
updateIsPublic (e) {
this.$store.commit('articles/UPDATE_IS_PUBLIC', e);
},
}
Store
UPDATE_IS_PUBLIC(state, value) {
state.article.is_public = value;
}
for bootstrap vue
if value is a "1" then value="1" and for "0" unchecked-value="0"
Related
i have tried already to assign the checkbox checked=true so the btn works.
i also tried to get to the value of the checkbox either from the e.target.value/checked but also no good came from it. if someone can help me i will be most greatful. thanks a lot
here is the code:
here is the checkbox element:
<label key={uuidv4()}>
<span>{masters[index].free_text}</span>
<input
type="checkBox"
name={masters[index].name}
id={masters[index].name}
checked={false}
required={masters[index].required}
// value={inputsAdContent.name?"true":"false"}
onChange={handleChangeAdContent}
/>
</label>
when the element is looking like this i get false at all times and it doesnt change
<label key={uuidv4()}>
<span>{masters[index].free_text}</span>
<input
type="checkBox"
name={masters[index].name}
id={masters[index].name}
required={masters[index].required}
value={inputsAdContent.name==="true" ? "true" : "false"}
onChange={handleChangeAdContent}
/>
</label>
and here is the onChange:
<label key={uuidv4()}>
<span>{masters[index].free_text}</span>
<input
type="checkBox"
name={masters[index].name}
id={masters[index].name}
required={masters[index].required}
value={inputsAdContent.name==="true" ? "true" : "false"}
onChange={handleChangeAdContent}
/>
</label>
at the console i get this msg:
air_conditioner: "on"
this is the state i'm using:
const [inputsAdContent, setInputsAdContent] = useState({});
thank you all very much!!!
I have a frustrating issue since last week. I am using a bootstrap checkbox inside a modal that I want to prefill with either true or false depending on the user selection for that boolean field. Even though I can get the value correctly, I can not get the tick on the checkbox working.
modal.html
<div class="input-group">
<label class="form-check-label" for="active">
Active
<span>
<input class="form-check-input" name="activeCheckbox" type="checkbox" id="active" onclick="handleCheckboxClick()">
</span>
</label>
</div>
handleCheckboxClick.js
$('.form-check-input').change(function () {
var check = $(this).prop('checked');
if(check === true) {
$('#active').prop('checked', true);
} else {
$('#active').prop('checked', false);
}
});
jQuery that prefills the modal
$('#modal-edit-config').on('shown.bs.modal', function() {
$('#classname').focus();
var selectedId = confId;
$.ajax({
url: 'getConfig',
data: {configId: selectedId},
success: function(data){
var config = data;
if(config != null) {
$('#id').val(config.id);
$('#className').val(config.className);
console.log(config.active);
config.active ? $('#active').attr('checked', true).change() : $('#active').attr('checked', false).change();
}
},
error: function(result) {
alert("Error getting the audit configId");
}
});
});
I tried both with prop() and attr() but, it doesn't work.
The js function works perfectly fine but when the modal pops up the prefilled value of the checkbox even though it is correct, it is not corresponding to the tick or untick in the UI.
Checkboxes change their visual "checked" status based on the existence of the attribute name itself, not its setting -- according to dev.mozilla.org: checked, Boolean; if present, the checkbox is toggled on by default
<p>Checkbox checked="true"</p>
<input type="checkbox" checked="true">
<p>Checkbox checked="false"</p>
<input type="checkbox" checked="false">
<p>Checkbox (no checked attr)</p>
<input type="checkbox">
You should update your checkbox generation JS to leave out the attribute itself: $('#active').attr('checked', false) will show a checked checkbox.
For regular checkboxes
You should use the proper HTML semantics with .form-check wrapper as described in Forms > Checkboxes & Radios:
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Check me out
</label>
</div>
As such, our <input>'s and <label>'s are sibling elements as opposed to an <input> within a <label>. This is slightly more verbose as you must specify id and for attributes to relate the <input> and <label>.
For custom checkboxes
To point you in the right direction you should read the section Custom forms > checkboxes.
Please note a label and input pairing wrapped in a div comes with a specific order.
The input goes first and is not wrapped by the label.
The reason is simple once you realize an input is an HTML element and they do not support "pseudo elements" :before and :after. These "pseudo class selectors" are required to introduce custom design on checkboxes/radios and so on.
Trivial and simplified CSS selector:
input[type="checkbox"]:checked ~ label:before { content: '✓' }
Otherwise there's no direct solution to reverse this selector like label input[type="checkbox"]:checked.
With that said, HTML is capable of handling your states by itself. No need for the handleCheckboxClick.js. You can then use .prop() to select by default in the ajax handler.
If you need to change the order visualy, you can introduce something like .custom-checkbox-reverse.
.custom-checkbox-reverse .custom-control-label::before,
.custom-checkbox-reverse .custom-control-label::after {
left: auto;
right: -1.5rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="customCheck1">
<label class="custom-control-label" for="customCheck1">Label after the checkbox</label>
</div>
<div class="custom-control custom-checkbox custom-checkbox-reverse">
<input type="checkbox" class="custom-control-input" id="customCheck2">
<label class="custom-control-label" for="customCheck2">Label before the checkbox</label>
</div>
FIDDLE to play around and enhance the padding for example as well.
A revision on the JavaScript part:
// what to expect here?
// should be sufficient to check if it has an id
// perhaps something else we can check? like config.status? Only you know at this point
// in fact it should always return the object or enter the error function
var checkboxState = false; // default
if(config && config.hasOwnProperty('id')) {
$('#id').val(config.id);
$('#className').val(config.className);
console.log(config.active); // expecting a boolean value
checkboxState = !!config.active; // double bang operator to make sure it's a boolean value
}
$('#active').prop('checked', checkboxState);
I have a list of Users to select for a team. Imagine that i select a User, he can either be active or inactive in his team. Now, if i don't select him at all, i should not be able to either activate or deactivate him.
This is made by a checkbox and a slider, like this:
When I click the checkbox, i need to disable the toggle. I have tried doing this by:
$("#2048").prop('disabled', true);
or
document.querySelector('[name="' + '#2048' + '"]').disabled = true;
Does not work either (And yes, i know that IDs should not be numbers, but it's because every toggle is inside a *ngFor. Still, i can use them as numbers, as jQuery can select them anyway)
Either way, i strongly believe that the only way to do something like this is to data-bind the 'disabled' attribute as some back-end variable that returns either a 'true' or 'false' value.
Something like:
<mat-slide-toggle
[id]='data.id'
class="status"
[disabled]='disableVariable'
>Active
</mat-slide-toggle>
and then:
disableVariable = someFunction(); //that returns true or false
This works, but the variable is 'too generic', i mean, every single slider will become disabled. Another problem is that this is not 'real-time', so i cant disable and enable multiple times.
Basically, it does not do the job.
What should i be doing here? If i had a way to select those tags using their unique ID's, that would fix the problem, but neither jQuery or Javascript's Query selector can disable or enable this tag.
EDIT:
A litle more of my code:
<div id="table" *ngFor="let data of User; let i = index">
<div [id]='data.id' *ngIf='data.user== 0' class="item">
<label class="container" style="width: 90%">
<input
type="checkbox"
*ngIf='data.status== 0'
id={{i}}
class="checkbox"
color=primary
checked>
<span class="checkmark"></span>
<div *ngIf='data.status== 0'>{{data.name}}
<mat-slide-toggle
[id]='data.id'
(change)=toggle(data.id)
*ngIf='data.status== 0'
color=primary
class="status"
>Active
</mat-slide-toggle>
</div>
</label>
</div>
</div>
When i add the ([ngModel)], my checkboxes stop working, and yes, i'm importing the FormsModule
You can use two-way binding to update the status of the checkbox as follows:
Add [(ngModel)] and disabled property to the input field
// Declare variable in component
CheckboxVar:boolean;
// In Html write below code
<input type="checkbox" [(ngModel)]="CheckboxVar" [disabled]="!CheckboxVar">
// Disabled checkbox when checkboxvar = false;
<input type="checkbox" [disabled]="!CheckboxVar">
Update CheckboxVar variable as per your need in your component.
Example with mat-slide-toggle
TS Code:
checked = false;
disabled = false;
HTML Code:
<input type="checkbox" [(ngModel)]="checked">
<mat-slide-toggle [disabled]="checked">
Slide me!
</mat-slide-toggle>
Now in the above example, if you checked the checkbox checked variable will be updated and if checked equals true then your toggle will be disabled.
If I understand the requirement correctly:
HTML Code:
<div *ngFor="let obj of list">
<mat-checkbox [(ngModel)]="obj.inTeam">In Team</mat-checkbox>
<br><br>
<mat-slide-toggle [(ngModel)]="obj.inTeam">Active</mat-slide-toggle>
</div>
TS Code:
list = [
{ id : 1,inTeam: false, isActive: false },
{ id : 3,inTeam: false, isActive: false },
{ id : 3,inTeam: false, isActive: false },
{ id : 4,inTeam: false, isActive: false }
]
StackBlitz
I'm not sure if I'm just stuck in a jQuery mindset but is there a way to update 2 model attributes with one radio button? Currently I have 2 radio buttons with one hidden. The visible one checks the second with an #click event that gets the next input and sets it to true.
var app = new Vue({
data: {
order: {
amount:
type:
}
},
methods: {
selectType: function(e) {
e.currentTarget.getElementSibling.checked = true;
}
}
});
<form>
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="small" style="display:none">
<input type="radio" v-model="order.amount" value=15 #click="selectType">$15</input><br>
<input type="radio" v-model="order.type" value="med" style="display:none" #click="selectType">
<input type="radio" v-model="order.amount" value=20 >$20</input><br>
<input type="radio" v-model="order.type" value="large" style="display:none">
</form>
The way I understand it, the v-model syntax is best for binding a single value. You could try to somehow make the value a JSON string and then decode it... but that sounds like a bad idea. Here are three ideas:
Using JQuery and Vue
Instead, you could give the radio buttons attributes for each value you want, and then parse out those attributes on the click callback. For example:
<input type="radio" name="rad" btn-amount="10" btn-type="small" #click="selectType($event)">$15 <br>
<input type="radio" name="rad" btn-amount="15" btn-type="med" #click="selectType">$15<br>
<input type="radio" name="rad" btn-amount="20" btn-type="large" #click="selectType">$20<br>
and then a method:
selectType: function(e) {
this.order.amount = $(e.currentTarget).attr('btn-amount');
this.order.type = $(e.currentTarget).attr('btn-type');
}
Here's a JSFiddle showing it in action.
Using Vue only
Alternatively, you could move the data for the options into the vue instance, rather than placing them on on the radio buttons. For example, add an options array to the data, and iterate over it in the HTML to create the buttons
<div v-for="option in options">
<input type="radio" name="rad" #click="selectType(option)">${{ option.amount }}
</div>
Notice that you can pass the current option in the for loop to the click handler! That means you can write selectType as:
selectType: function(option) {
this.order = option;
}
This is very clean, and what I recommend if you plan on keeping the radio-button functionality simple.
Here is a JSFiddle showing it in action.
Using Vue Components
But, if you plan on making things more complex you may want to encapsulate the radio button functionality into a component.
Consider the template:
<template id="radio-order">
<div>
<input type="radio" :name="group" #click="setOrder">${{ amount }}
</div>
</template>
and its associated component:
Vue.component('radio-order', {
template: '#radio-order',
props: ['group', 'amount', 'type'],
methods: {
'setOrder': function() {
this.$dispatch('set-order', {
amount: this.amount,
type: this.type
})
}
}
});
Now you can make <radio-order> components that dispatch a set-order event when clicked. The parent instance can listen for these events and act appropriately.
Admittedly, this method is more verbose. But, if you're thinking of implementing more complex functionality, it's probably the way to go.
Here's a JSFiddle of it in action.
Of course, there are many more ways to solve the problem, but I hope these ideas help!
Here is the code on selection of any one of the radio button i need to get the value
<label ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="{{surveyData.SurveyTypeName}}" />
{{SurveyType.Name}}
</label>
You should assign value from your repeat-loop not from model value and no need to use {{}} for ng-value
so use ng-value="SurveyType.Name" instead of ng-value="{{surveyData.SurveyTypeName}}" so selected radio button value set to surveyData.SurveyTypeName.
If you want to select anyone by default you can assign value to surveyData.SurveyTypeName like $scope.surveyData={SurveyTypeName: 'second'} then that radio button shown as selected that has value second.
HTML:
<label ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="SurveyType.Name" />
{{SurveyType.Name}}
</label>
PLUNKER DEMO
Your HTML should be like this.
<input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeName" ng-value="{{surveyData.SurveyTypeName}}" ng-change="getval($index)"/>
Js
$scope.getval = function (index){
var servetypename =SurveyTypes[index];
var data =servetypename.SurveyTypeName
}
Don't know from surveyData.SurveyTypeName is coming from.
<li ng-repeat="SurveyType in SurveyTypes">
<input type="radio" name="SurveyTypeName" ng-model="$parent.rdoSelected" ng-value="SurveyType.SurveyTypeName" />
{{SurveyType.Name}}
</li>
PLUNKER