how to make radio buttons selected in angularjs - html

i am new to angularjs and javascript,I am having a list of radio buttons and have to make some of them selected,so can anybuddy please tell me how to achieve this?I tried ng-value=true with no luck,my code is as below:
<ons-list-item modifier="tappable" ng-repeat="area in vm.AreaList" >
<label class="radio-button radio-button--list-item line-h45">
<input type="radio" ng-bind="area.name" ng-model="vm.selectedArea" name="area" ng-value="area.code" >
<div class="radio-button__checkmark radio-button--list-item__checkmark">
</div>
{{area.name}}
</label>
</ons-list-item>

you can do something like this in your controller:
$scope.results = {
favorites: [{
id: "WatchList1",
title: "WatchList1"
}, {
id: "WatchList2",
title: "WatchList2"
}, {
id: "WatchList3",
title: "WatchList3"
}]
};
$scope.selectedRow = {
id: 'WatchList2'
};
$scope.event = {
type: {
checked: true
}
}
and your html:
<div>
<div ng-repeat="row in results.favorites">
<input type="radio" ng-model="selectedRow.id" value="{{ row.id }}" style="opacity: 1;" class="pointer" />
<span>{{ row.title }}</span>
</div>
</div>
Single box

You should use ngChecked for that.
https://docs.angularjs.org/api/ng/directive/ngChecked
<ons-list-item modifier="tappable" ng-repeat="area in vm.AreaList" >
<label class="radio-button radio-button--list-item line-h45">
<input type="radio" ng-bind="area.name" ng-model="vm.selectedArea" name="area" ng-value="area.code"
ng-checked="true">
<div class="radio-button__checkmark radio-button--list-item__checkmark">
</div>
{{area.name}}
</label>
</ons-list-item>

Only one radio button can be selected at a time.
If you want multiple selected items, then use checkbox and to select, make model value equal to value attribute.

Related

Display all the data in a checkbox that are coming from the api in vuejs

I am facing an issue where i want to display the data of an array from api in checkbox. I have list of checkbox calling from another api and i want to show the selected values with checked in that list of checkbox but i cannot
Here is the sample of code:
<ul class="checkboxes">
<li v-for="(role, i) in roles" :key="i">
<input
:id="'checkbox' + i"
type="checkbox"
v-model="selected"
:value="role"
/>
{{ role.name }}
</li>
</ul>
All though all the checkbox are displaying but it is not displaying the ones with checked that are coming from backend.
For example: i have 10 values inside roles. but not showing checked in the page.
Roles looks like this:
roles:['x:list', 'y:list']
please help
I built a sample component showing how to bind an array of roles to checkboxes:
<template>
<div class="bind-multiple-checkboxes">
<h3>Select Roles</h3>
<div class="row">
<div class="col-md-6">
<div class="form-check" v-for="(role, index) in roles" :key="index">
<input class="form-check-input" type="checkbox" :id="'checkbox' + index" v-model="role.selected">
<label class="form-check-label" :for="'checkbox' + index">
{{ role.name }}
</label>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
roles: [
{
name: 'role1',
selected: true
},
{
name: 'role2',
selected: false
},
{
name: 'role3',
selected: false
},
{
name: 'role4',
selected: true
},
]
}
}
}
</script>
it is important that you have an empty array to bind the selected values in two ways. note that role.name does not exist, since role is a string in your array:
new Vue({
el: '#app',
data: {
roles: ['x:list', 'y:list', 'z:list'],
selected: ['z:list'] // fill if you want a checkbox prefilled
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='app'>
<ul class="checkboxes">
<li v-for="role in roles" :key="role.id">
<label>
<input
type="checkbox"
:value="role"
v-model="selected"
/>
{{ role }}</label>
</li>
</ul>
<p>{{ selected }}</p>
</div>
you can read more about input bindings here

Add multiple checkboxes based on input length in Angular

Currently, I have a single checkbox in my Angular application which I plot using the HTML code:
<input type="checkbox" id="box1" value="Apple">
<label for="box1"> Apple</label>
However, I now need to tweak the functionality such that the number of checkboxes is dependant on the array input. Also, the contents of the arrays should be the labels for the checkboxes.
For ex:
If my array is arr = ['Apple', 'Mango','Banana'], I should get 3 checkboxes (as the length of arr is 3) like this:
How can I do this?
use *ngFor for acheiving this
app.component.html
<div *ngFor="let item of arr;">
<input type="checkbox" id="{{item}}" [value]="item " (change)="getItem($event)">
<label for="{{item}}"> {{item }}</label>
</div>
app.component.ts
arr = ['Apple', 'Mango','Banana'];
getItem(item) {
//check if the checkbox selected or not
if(item.target.checked) {
let value = item.target.value;
console.log(value);
//Do your thing here
}
}
Hope this help's :)
There is multiple way to achieve this.
HTML
<div *ngFor="let item of array; let i = index">
<input type="checkbox" [checked]="item.status" (click)="checked(i)">
<label> {{item.name}}</label>
</div>
<div *ngFor="let item of arr;">
<input type="checkbox" id="{{item}}" [value]="item ">
<label for="{{item}}"> {{item }}</label>
</div>
Class
array = [
{ name: "Apple", status: true },
{ name: "Mango", status: true },
{ name: "Banana", status: true }
];
checked(i) {
this.array[i].status = !this.array[i].status;
}
arr = ["Apple", "Mango", "Banana"];
You can also find working link: stackblitz

React - Deselecting the checkbox doesn't make div to dissapear

I'm currently messing around with Reactjs and don't know where exactly my problem lays. I wan't to render an input field if a certain chekbox is selected (requiredRoleResponsible in this case). If i check it first time to true it works fine, but if I deselect it, it won't disappear. Maybe i missing something?
class ProccessForm extends React.Component {
constructor(props) {
super(props)
this.state = { name: '', description: '', requireSupervisor: false, requireRoleResponsible: false, roleResponsible: '' }
this.handleNameChange = this.handleNameChange.bind(this);
this.handleDescriptionChange = this.handleDescriptionChange.bind(this);
this.handleSupervisorCheckbox = this.handleSupervisorCheckbox.bind(this);
this.handleRoleResponsibleCheckbox = this.handleRoleResponsibleCheckbox.bind(this);
this.handleRoleResponsibleChange = this.handleRoleResponsibleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e, data) {
e.preventDefault();
const name = this.state.name.trim();
const description = this.state.description.trim();
if (!name || !description)
return;
this.props.onProcessSubmit({ name: name, description: description });
this.setState({ name: '', description: '' });
}
handleSupervisorCheckbox(e) {
this.setState({requireSupervisor: Boolean(e.target.value)});
}
handleRoleResponsibleCheckbox(e) {
this.setState({requireRoleResponsible: Boolean(e.target.value)});
}
handleRoleResponsibleChange(e) {
this.setState({roleResponsible: e.target.value});
}
handleNameChange(e) {
this.setState({ name: e.target.value })
}
handleDescriptionChange(e) {
this.setState({ description: e.target.value })
}
render() {
return (
<div className="panel-body">
<form className="processForm" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="inputName">Name</label>
<input className="form-control" id="inputName" type="text" placeholder="Prozessname" value={this.state.name} onChange={this.handleNameChange} />
</div>
<div className="form-group">
<label htmlFor="inputDescription">Beschreibung</label>
<textarea className="form-control" id="inputDescription" type="text" placeholder="Prozessbeschreibung" value={this.state.description} onChange={this.handleDescriptionChange} />
</div>
<span>Welche Genehmigungen werden benötigt?</span>
<div className="checkbox">
<label><input type="checkbox" value={this.state.requireSupervisor} onChange={this.handleRoleResponsibleCheckbox}/>Vorgesetzer</label>
</div>
<div className="checkbox">
<label><input type="checkbox" value={this.state.requireRoleResponsible} onChange={this.handleRoleResponsibleCheckbox}/>Rollenverantwortlicher</label>
</div>
{this.state.requireRoleResponsible ?
<div className="form-group">
<label htmlFor="inputRoleResp">Name</label>
<input className="form-control" id="inputRoleResp" type="text" placeholder="Rollenverantwortlicher" value={this.state.roleResponsible} onChange={this.handleRoleResponsibleChange} />
</div> : null}
<div>
<input type="submit" value="erstellen" />
</div>
</form>
</div>
);
}
}
I tried different approaches I seen online so far. Making the second part of the if to null like currently in my code. Just to use this.state.requireRoleResponsible && the to render part and in the handler to make explicitely a boolean out of the value
Thanks for your help
For checkbox you need to use checked instead of value.
Checked will determined if the checkbox is checked or not. Value is just a property to hold.
In this case you need to change:
<input type="checkbox" value={this.state.requireRoleResponsible}
onChange={this.handleRoleResponsibleCheckbox}/>Rollenverantwortlicher</label>
To:
<input type="checkbox" checked={this.state.requireRoleResponsible}
onChange={this.handleRoleResponsibleCheckbox}/>Rollenverantwortlicher</label>
And change the handler to:
handleRoleResponsibleCheckbox(e) {
this.setState({requireRoleResponsible: e.target.checked});
}
With checkbox you should use checked instead of value ( should use value attr for type: text , select , ... )
And in 2 function handler for your checkbox , i think you can use like this :
handleRoleResponsibleCheckbox(e) {
//this.setState({requireRoleResponsible: Boolean(e.target.value)});
this.setState((prevState)=>{
return {
requireRoleResponsible: !prevState.requireRoleResponsible
}
})
}
with prevState is current state before you update

checked the all checkboxes of form in angularjs

Hi i have form in angularjs and that form have many checkboxes on clicking first checkbox i,e check All i want to checked the all checkboxes . how i can i do that with angular for each field loop here is my sample code I am trying in code snipt.
vm.asas = function() {
angular.forEach($scope.quizSettingsForm, function(field) {
console.log(field);
angular.forEach(field, function(errorField) {
errorField.$setTouched();
});
});
console.log(vm.QuizSettings);
};
<form name="quizSettingsForm" novalidate>
<div class="panel panel-default">
<div class="panel-heading">
QUIZ SETTINGS
</div>
<div class="panel-body">
<ul>
<li>
<div class="checkbox">
<input type="checkbox" id="checkall" ng-model="vm.checkAll" ng-click="vm.asas()" />
<label for="checkall">Check /Uncheck ALL</label>
</div>
</li>
<li>
<div class="checkbox">
<input type="checkbox" ng-model="vm.QuizSettings.IsOpened" id="Cohort" />
<label for="Cohort">Have a open Quiz</label>
</div>
</li>
<li>
<div class="checkbox">
<input type="checkbox" ng-model="vm.QuizSettings.IsMandatory" id="mandatory" />
<label for="mandatory">Is Mandatory</label>
</div>
</li>
<li>
<div class="checkbox counterdiv">
<input type="checkbox" ng-model="vm.QuizSettings.ShouldExpireAfterExpiry" id="invitation" />
<label for="invitation"> <p>The quiz will expire <input type="number" ng-model="vm.QuizSettings.Expiry" ng-min="1" name="expiry"> days after invitation</p></label>
<span class="validation-message" ng-show=" vm.QuizSettings.ShouldExpireAfterExpiry && quizSettingsForm.expiry.$touched && quizSettingsForm.expiry.$error.min"><i class="fa fa-warning"></i> The minimum value is 1.</span>
</div>
</li>
<li>
<div class="checkbox">
<input type="checkbox" ng-model="vm.QuizSettings.AllowRetakes" id="dontallow" />
<label for="dontallow">Allow Retake and dont allow more than </label>
<input type="number" ng-model="vm.QuizSettings.AlllowMoreThen" ng-min="1" name="dontallow"><span style="color: #696969;font-size: 18px;font-weight: normal;"> Retakes </span>
<span class="validation-message" ng-show="quizSettingsForm.dontallow.$touched && quizSettingsForm.dontallow.$error.min"><i class="fa fa-warning"></i> The minimum value is 1.</span>
</div>
</li>
</ul>
</div>
</div>
</form>
One Approach (if checkbox properties are on same object with other properties)
You could (not necessarily should) store property names in an array, and then you could use a forEach loop to set the property itself on the vm.quizSettings object:
function selectAll(){
var myArray = [
"IsOpened",
"IsMandatory",
"ShouldExpireAfterExpiry"
];
angular.forEach(myArray, function(propName){
vm.QuizSettings[propName] = true;
});
}
Much Better (if checkbox properties are alone on same object)
It would be much better if you could avoid storing property names as strings. If all of your checkbox boolean properties to update were alone on it's own object, then it becomes much cleaner:
function selectAll(){
var myArray = Object.keys(vm.QuizSettings);
angular.forEach(myArray, function(propName){
vm.QuizSettings[propName] = true;
});
}
Better Still (simply decorate the checkboxes that this behavior should apply to)
Create a custom directive selectAllListener that listens to a "SelectAll" event and updates ngModel value to true when that event is raised.
function thisDirective() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, el, attr, ngModel){
scope.$on("SelectAll", function(){
ngModel.$setViewValue(true);
ngModel.$render();
});
}
}
}
Add the select-all-listener decorator directive to your checkboxes:
<li>
<div class="checkbox" >
<input select-all-listener type="checkbox" id="checkall" ng-model="vm.checkAll" ng-click="vm.asas()"/>
<label for="checkall" >Check /Uncheck ALL</label>
</div>
</li>
Raise the event from within your controller:
function selectAll(){
$rootScope.$broadcast("SelectAll");
}
Build an object for your form where isChecked key refers to checkbox value and name refers the label and value refers the model or value of input.
$scope.FormAttributeList = [
{
id: 1,
name: "xyz",
value: "xyz",
isChecked: false
},
{
id: 2,
name: "xyz",
value: "xyz",
isChecked: false
},
{
id: 3,
name: "xyz",
value: "xyz",
isChecked: false
},
{
id: 4,
name: "xyz",
value: "xyz",
isChecked: false
}
]
your code will be like
<div class="panel-body">
<ul>
<li>
<div class="checkbox" >
<input type="checkbox" id="checkall" ng-model="vm.checkAll" ng-click="selectAll(vm.checkAll,FormAttributeList)"/>
<label for="checkall" >Check /Uncheck ALL</label>
</div>
</li>
<li ng-repeat="item in FormAttributeList">
<div class="checkbox">
<input type="checkbox" ng-model="item.value" id="item.id" />
<label for="Cohort" >{{item.name}}</label>
</div>
</li>
</div>
Now create a function like
$scope.selectAll = function(checkAll,List) {
angular.forEach(list,function(value,key){
value.isChecked = checkAll;
});
};
This is the best way to do what you want it'll remove your unnecessary code.

Knockout Binding Messes up Radio Button Formatting

As a prototype, I hard coded a radio button list, just to work out the CSS, etc. When I converted it to be generated from a JSON list using Knockout, however, the formatting went crazy. Here is the original HTML:
<input id="pcp1" type="radio" name="pcp" /><label for="pcp1"><span></span>One</label><br />
<input id="pcp2" type="radio" name="pcp" /><label for="pcp2"><span></span>Two</label><br />
<input id="pcp3" type="radio" name="pcp" /><label for="pcp3"><span></span>Three</label><br />
Here is the Knockout version. It gets the data from the ajax call correctly (3 items with the correct text):
<div data-bind="foreach: PrimaryCareProviders">
<input data-bind="attr: { id: Id }" type="radio" name="pcp" /><label data-bind="attr: { for: Id }"><span></span><span data-bind="text:Name"></span></label><br/>
</div>
What's going on here?
Thanks,
Jay
This looks fine. You might want to inspect your HTML elements in your debugger. Also, if you're using some kind of toolkit to style things, that would be a problem.
v = {
PrimaryCareProviders: [{
Id: 1, Name: 'One'
}, {
Id: 2, Name: 'Two'
}, {
Id: 3, Name: 'Three'
}]
};
ko.applyBindings(v);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: PrimaryCareProviders">
<input data-bind="attr: { id: Id }" type="radio" name="pcp" />
<label data-bind="attr: { for: Id }">
<span></span>
<span data-bind="text:Name"></span>
</label>
<br/>
</div>
The problem is that I added a second span to do the Knockout binding of the Name field. I assumed I needed to use an HTML element to bind to. Turns out you don't need to bind to an HTML element in Knockout. You can use "containerless syntax."
So, I replaced my second <span> with this, and that fixed it:
<!--ko text:Name--><!--/ko-->