Multiple check box not working when it's value same vuejs - checkbox

When I check Apple it's all check Pineapple. When I unchecked Pineapple it's also unchecked Apple.
both Tag id different. How can I check only one Apple instead of Pineapple?
var demo = new Vue({
el: '#demo',
data: {
checkedNames: []
},
computed: {
computedNames() {
let names = this.checkedNames;
return names.toString();
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<input type="checkbox" id="50" value="50" v-model="checkedNames">
<label for="Apple">Apple</label>
<input type="checkbox" id="51" value="51" v-model="checkedNames">
<label for="Banana">Banana</label>
<input type="checkbox" id="52" value="50" v-model="checkedNames">
<label for="Pineapple">Pineapple</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
<span>Computed names (reversed order): {{ computedNames }}</span>
</div>

Vue is data-driven. Since both your Apple and Pineapple checkboxes have the same value, Vue considers them to be the same.
It sounds like you want to use separate objects entirely so try this
var demo = new Vue({
el: '#demo',
data: () => ({
options: [{
id: 50,
label: "Apple",
price: 50
}, {
id: 51,
label: "Banana",
price: 51
}, {
id: 52,
label: "Pineapple",
price: 50
}],
selections: []
}),
computed: {
computedNames: ({ selections }) =>
selections.map(({ label }) => label).join(", ")
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="demo">
<template v-for="fruit in options">
<input
:key="fruit.id"
type="checkbox"
:value="fruit"
v-model="selections"
:id="`fruit_${fruit.id}`"
>
<label :for="`fruit_${fruit.id}`">{{ fruit.label }}</label>
</template>
<br>
<span>Computed names: {{ computedNames }}</span>
<pre>Selections: {{ selections }}</pre>
</div>

Related

Get value from multiple checkbox and input to an array

How we can get the value of checkbox an input to an array?
Here is my code, I've tried this:
<cbComp
v-for="name in names"
v-bind:key="name"
v-model="selected_name[name]">
<span> {{ name }} </span>
</cbComp>
Name: {{ selected_name }}
data () {
return {
names: ['Michael', 'Millie', 'Brown'],
selected_name: []
}
},
This was the cbComp template:
<template>
<label class="checkbox">
<input
:id="cb"
type="checkbox"
:value="modelValue"
v-model="computedValue"
>
<label
:for="cb">
<slot/>
</label>
</label>
</template>
This is the javascript:
export default {
data: {
updateValue: this.value
},
props: {
value: undefined,
modelValue: {
type: undefined,
default: false
}
},
computed: {
computedValue: {
get () {
return this.updateValue
},
set (value) {
this.updateValue = value
this.$emit('input', value)
}
}
},
watch: {
value (value) {
this.updateValue = value
}
}
}
It turns out there is no error, and the selected name won't appear on {{ selected_name }}
You simply need to bind your v-model to the selected_name property. Here is a bare minimum example for you to work off of:
<html>
<div id="app">
<p>Names: {{ selected_name.join(', ') }}</p>
<label for="maxCheckbox">Max</label>
<input type="checkbox" value="Max" v-model="selected_name" id="maxCheckbox">
<label for="markCheckbox">Mark</label>
<input type="checkbox" value="Mark" v-model="selected_name" id="markCheckbox">
<label for="johnCheckbox">John</label>
<input type="checkbox" value="John" v-model="selected_name" id="johnCheckbox">
</div>
<script src="https://unpkg.com/vue#2"></script>
<script>
new Vue({
el: '#app',
data() {
return {
selected_name: []
}
}
});
</script>
</html>
As a side note, I would probably rename your selected_name to be more clear like selected_names or more commonly you'll find selectedNames camelCase.

angular radio button set checked

i have multiple radio button groups
i need to set one of each group (maybe none) as selected
datasource
html Code
<div class='row' ng-show="mk.selectedTypeAttributesID.length != 0">
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" value="{{val.val}}" ng-click="mk.AttChange(att.id,val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
i need to use the value of 'Selected' On the datasource to set the checkbox
source Update
You need to use ng-model to select the radio button..
Where ng-model holds the selected value as shown below.
$scope.options = [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}];
$scope.selected = undefined;
var findResult = $scope.options.find(function(x){ return x.Selected == true });
if(findResult){
$scope.selected = findResult.val;
}
Here's a JSFiddle
Edit: Since the sources of the checkboxes are dynamic then build a dynamic selection tree for modal to bind to..
Here's an example:
$scope.options = [{ 0 : [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}]}, { 1 : [{ Selected: false, val: "2" }, { Selected: true, val: "1" }]}];
$scope.choices = [];
for(var i = 0; i < Object.keys($scope.options).length; i++){
var keys = Object.keys($scope.options);
$scope.choices.push({ Id: keys[i], Value: $scope.options[i][keys[i]].find(function(x){ return x.Selected == true }).val });
}
JSFiddle
Are you looking for a solution like so?
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.selectedTypeAttributesID = [{
id: 1,
Values: [{
val: "red",
selected: ""
}, {
val: "green",
selected: ""
}, {
val: "blue",
selected: ""
}]
},
{
id: 2,
Values: [{
val: "1",
selected: ""
}, {
val: "2",
selected: ""
}, {
val: "3",
selected: ""
}]
}
];
$scope.setVal = function(att, index, val) {
for (var k of att.Values) {
k.selected = "";
}
att.Values[index].selected = val;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<div class='row'>
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" ng-value="val.val" ng-click="setVal(att, $index, val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
<pre>{{selectedTypeAttributesID | json}}</pre>
</div>

Adding the input fields dynamically from nested json object in angulajs

var inputs={
'firstname': '',
'lastName':'',
'account':{
'role':'',
'status':''
}
}
This is my model array. I want to display it dynamically in Webpage and by modifying the json array the changes should affect the form too.
Here is the image
UPD:
for your situation, you can use ng-switch to generate elements according to conditions.
Notice(already included in the code snippet):
ng-repeat will generate it's own scope, so your model won't update unless you bind it with the original scope. ref here.
OLD ANSWER:
use ng-model to implement two-way-databinding.
refer the code snippet below:
angular.module("app", []).controller("myCtrl", function($scope) {
$scope.inputs = {
'firstname': 'test first name',
'lastName': 'test last name',
'account': {
'role': 'test role',
'status': 'test status'
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<!-- First Name: <input type="text" ng-model="inputs.firstname"><br>
Last Name: <input type="text" ng-model="inputs.lastName"><br> Account Role: <input type="text" ng-model="inputs.account.role"><br>
Account Status: <input type="text" ng-model="inputs.account.status"><br> -->
<div ng-repeat="(key1, value) in inputs" ng-switch="key1">
<div ng-switch-when="account">
<div ng-repeat="(key2, value2) in value">
{{key1 | uppercase}} => {{ key2 | uppercase}}
<input type="text" ng-model="inputs[key1][key2]">
</div>
</div>
<div ng-switch-default>
{{key1 | uppercase}}
<input type="text" ng-model="inputs[key1]">
</div>
</div>
{{inputs}}
</div>
/My html should look like this/
<head>
<script data-require="angular.js#1.4.1" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<script type="text/ng-template" id="tree-structure">
<label>{{dt}}</label><input type="text" name="" value="{{dt.label}}">
<ul class="childElement">
<li ng-repeat="dt in dt.nodes" ng-include="'tree-structure'">
</li>
</ul>
</script>
<ul class="parentList">
<li ng-repeat="(key, value) in inputs" >
<div ng-repeat="(key1, value1) in value">
<label>{{key1}}</label>
<input type="text" name="" value="{{value1}}">
<!-- <div ng-repeat="(key2, value2) in value1">
<label>{{key2}}</label><input type="text" name="" value="{{value2}}">
</div> -->
</div>
<div ></div>
</li>
</div>
</ul>
</body>
</html>
Some observations :
Your JSON should be formatted properly with type of the field.
If you want to access the object properties as a form fields then it should be structured in a good way so that we can dynamically add the type of the field as well.
[{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}]
As your JSON have nested objects. So, first iterate it recursively and create one dimensional array then create the fields using 1D array.
DEMO
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function($scope) {
var inputs = [{
name: 'firstName',
type: 'text'
}, {
name: 'lastname',
type: 'text'
}, {
account: [{
name: 'role',
type: 'text'
}, {
name: 'status',
type: 'text'
}]
}];
$scope.fields = [];
function structuredObj(obj) {
for (var i in obj) {
if (obj[i].type == 'text') {
$scope.fields.push(obj[i]);
} else {
structuredObj(obj[i])
}
}
};
structuredObj(inputs);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<form name="myForm" novalidate>
<div ng-repeat="item in fields" class="form-group">
<input
name="item.name"
type="{{ item.type }}"
placeholder="{{ item.name }}"
ng-model="item.value"
required />
</div>
<button ng-disabled="myForm.$invalid">Submit</button>
</form>
</div>
<div ng-repeat="(key1, value1) in myPersonObj">
<div ng-repeat="(key, value) in value1">
<label>{{key}}</label>
<input type="text" name="" value="{{value}}">
</div>
</div>
var app = angular.module("test",[]);
app.controller("MainCtrl",function($scope){
$scope.inputs = [
{
"firstname" : "Test"
},{
"lastname" : "Test1"
},{
"Account" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account1" : [
{"role" : "Test3"},
{"status" : "Test4"},
]
},
{
"Account2" : [
{"role" : {
'dim3': {
'dim4':{
'dim5':'cccc'
}
}
}
},
{"status" : "Test4"},
]
}
];
$scope.person = [];
$scope.myPersonObj = [];
/*console.log($scope.keys(inputs));*/
$scope.checkIndex1 = function(arg, myPersonObj)
{
if (angular.isArray(arg) || angular.isObject(arg)) {
angular.forEach(arg, function (value, key) {
console.log(value);
if(angular.isObject(value) || angular.isArray(value))
{
$scope.checkIndex1(value, myPersonObj);
}
else
{
console.log("pushing");
myPersonObj.push(arg);
}
});
}
else
{
console.log("pushing1");
myPersonObj.push(arg);
}
}
$scope.checkIndex1($scope.inputs, $scope.myPersonObj);
console.log("myPersonObj :"+ JSON.stringify($scope.myPersonObj));
console.log($scope.inputs);

Select value not selected in Angularjs

I have this html markup:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label><div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name for opt in propGradings track by opt.id"> <option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option> </select>
</div>
</div>
This static array to fill in the dropdown:
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
I'm able to load the items in the dropdown, but I'm not able to preselect the correct value based on the prop.Grade value.
HTML Output:
Any idea what am I doing wrong?
When selecting options from a dropdown, type matters for binding purposes. When using ng-options, you can use as to bind something to the model as a non-string value. In your case, you may want to bind to the integer value of the id.
Syntax: select as label for value in array
> select: The value that gets bound to ng-model
> label: What value visibly shows up in the dropdown
> value: Current item in array
> array: Data source for generating the options
Example of binding to an integer value:
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: 1}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with an integer value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.id as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>
Example of binding to a string value:
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.props = [{Grade: "1"}];
$scope.propGradings = [{ name: "1", id: 1 }, { name: "2", id: 2 }, { name: "3", id: 3 }, { name: "4", id: 4 }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Binding with a string value:
<div ng-repeat="prop in props" style="margin-bottom: 10px;">
<label class="col-md-4 control-label">Property {{$index + 1}} ({{prop.AddressLine1}})</label>
<div class="col-md-8">
<select ng-model="prop.Grade" class="form-control" ng-options="opt.name as opt.name for opt in propGradings">
<option ng-selected="{{option.id == prop.Grade}}" ng-repeat="option in propGradings" ng-value="{{option.id}}">{{option.name}}</option>
</select>
</div>
</div>
</div>

How to get data from radio buttons? angularjs

i wona get price and name of chosen radio buttons. its easy with simple html tags.
But I stacked when i trying generate radio buttons via angularjs from array (items)
Help!
http://jsfiddle.net/hanze/j9x23apu/
html
<h1>Select </h1>
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items">
<div class="radio">
<label>
<input type="radio" name="item" ng-model="item" ng-checked="{{item.checked}}">
{{item.name}} +{{item.price}} $.</label>
</div>
</div>
Your choice: {{}} **what i must write here?**
<br>
Price: {{}} **and here?**
</div>
js
OrderCtrl = function ($scope) {
$scope.items = [{
name: 'None',
value: "no",
price: 0,
checked: true
}, {
name: 'Black',
value: "black",
price: 99,
checked: false
}, {
name: 'White',
value: "white",
price: 99,
checked: false
}, {
name: 'Barhat',
value: "barhat",
price: 49,
checked: false
}, {
name: 'Barhat',
value: "cream",
price: 49,
checked: false
}]
You can look at the angularjs documentaion about radio buttons here. You don't need to use ng-checked here. Use ng-value to set the value when redio is selected.
I changed your jsfiddle post.
Your are missing the closing tag for your input. And when you have ng-repeat you have a seperate scope. In this case you need $parent.selectedItem to hold your selected elements.
I have updated the JSFiddle with a working state solution.
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items" style="text-indent: 30px">
<input type="radio" name="itemRadio" ng-model="$parent.selectedItem" ng-value="item.name"/>
{{item.name + '-' + item.price}}$.
</div>
Your choice: {{selectedItem}}
</div>
jsFiddle: http://jsfiddle.net/j9x23apu/16/
html
<div ng-app="" ng-controller="OrderCtrl">
<div ng-repeat="item in items" style="text-indent: 30px">
<label>
<input type="radio" name="item" ng-checked="{{item.checked}}" ng-click="change_item($event)" item-name="{{item.name}}" item-price="{{item.price}}" /> {{item.name}} + {{item.price}}
</label>
</div>
Your choice: {{selectedName}}
<br />
Price: {{selectedPrice}}
</div>
js
OrderCtrl = function ($scope) {
$scope.change_item = function(e) {
$scope.selectedName = e.target.attributes['item-name'].value;
$scope.selectedPrice = e.target.attributes['item-price'].value;
};
$scope.items = [{
name: 'None',
value: "no",
price: 0,
checked: true
}, {
name: 'Black',
value: "black",
price: 99,
checked: false
}, {
name: 'White',
value: "white",
price: 99,
checked: false
}, {
name: 'Barhat',
value: "barhat",
price: 49,
checked: false
}, {
name: 'Barhat',
value: "cream",
price: 49,
checked: false
}]
}

Resources