Javascript/Jquery - Calculate values and show inside a div - javascript

I've got to write it down a scheme to show you what I am trying to develop. As you can see in the image below, there is a radio and a select area. Depending on the users choice on both areas there will be different values to consider in the function. The red values are related to the dropdown list. If you choose the op1 and "a" on the dropdown, "a" will be 2160. If you choose op3 and "c" on the dropdown, "c" will be 3888 and so on. The total will be shown inside the #total div and the values related to the choice on the radio and the dropdown will be shown inside other two divs #subRadio and #subDrop (the value that is been added to the radio value).
When I tried to solve it I end up with a huge list of if's that actually didn't worked at all, so I ask you guys your help on this problem.
Just in case anyone ask, I'll put here the code I started to write:
<form class="form-horizontal text-left" id="meishi">
<div class="form-group">
<div class="col-lg-2 topic">
<label>Design</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" name="design" value="10800">op1
</label>
</div>
<div class="col-lg-4">
<label class="radio-inline">
<input type="radio" name="design" value="14040">op2
</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" name="design" value="16200">op3
</label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2" for="qtt">Quantity</label>
<select id="qtt" class="col-lg-3" name="qtt">
<option value="">Choose one</option>
<option value="a">100</option>
<option value="b">200</option>
<option value="c">300</option>
</select>
</div>
</form>
$(document).ready(function(){
$("#msQtt").change(function(){
var design = $('input[name=design]:checked').val();
var qtt = $("#qtt option:selected").val();
if(design == "10800" && qtt == "a"){
$('#subRadio').text('$ 10800')
$('#subDrop').text('$ 2160')
$('#total').text('$ 12960')
}
else if(design == "10800" && qtt == "b"){
$('#subRadio').text('$ 10800')
$('#subDrop').text('$ 2484')
$('#total').text('$ 13284')
}
});
});
Thank you very much!

I hope that's what are you looking for DEMO
<form class="form-horizontal text-left" id="meishi">
<div class="form-group">
<div class="col-lg-2 topic">
<label>Design</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" data-drop-a="2160" data-drop-b="2484" data-drop-c="2808" name="design" value="10800">op1
</label>
</div>
<div class="col-lg-4">
<label class="radio-inline">
<input type="radio" data-drop-a="2808" data-drop-b="3132" data-drop-c="3456" name="design" value="14040">op2
</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" data-drop-a="3240" data-drop-b="3564" data-drop-c="3888" name="design" value="16200">op3
</label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2" for="qtt">Quantity</label>
<select id="qtt" class="col-lg-3" name="qtt">
<option value="">Choose one</option>
<option value="a">100</option>
<option value="b">200</option>
<option value="c">300</option>
</select>
</div>
</form>
_
<script type="text/javascript">
$(document).ready(function(){
$("input[name=design], #qtt").on('change',function(){
var design = $('input[name=design]:checked');
var designVal = parseInt(design.val());
var qtt = $("#qtt").val();
var subDrop=parseInt(design.data('drop-'+qtt));
if (!subDrop) subDrop=0;
if (!designVal) designVal=0;
$('#subRadio').text(designVal)
$('#subDrop').text(subDrop)
$('#total').text(designVal+subDrop)
});
});
</script>

Create an object where your store your data:
var data = {
'opt10800' : {
'a' : 2160 ,
'b' : 2484 ,
'c' : 2808
},
'opt14040' : {
'a' : 2808 ,
'b' : 3132 ,
'c' : 3456
},
'opt16200': {
'a' : 3240 ,
'b' : 3564 ,
'c' : 3888
}
};
Then, when either the dropdown or radio buttons are changed, take the values from the object and put them inside the spans:
$(function() {
$('[name=design],[name=qtt]').on('change', function() {
var r = $('[name=design]:checked').val() ,
d = $('[name=qtt] option:selected').val();
if( r != '' && d != '') {
var s = data['opt'+r][d] ,
t = parseInt( r ) + parseInt( s );
$('#subRadio').text( r + ' + ' );
$('#subDrop').text( s + ' = ' );
$('#total').text( t );
}
});
});
Full demo:
var data = {
'opt10800' : {
'a' : 2160 ,
'b' : 2484 ,
'c' : 2808
},
'opt14040' : {
'a' : 2808 ,
'b' : 3132 ,
'c' : 3456
},
'opt16200': {
'a' : 3240 ,
'b' : 3564 ,
'c' : 3888
}
};
$(function() {
$('[name=design],[name=qtt]').on('change', function() {
var r = $('[name=design]:checked').val() ,
d = $('[name=qtt] option:selected').val();
if( r != '' && d != '') {
var s = data['opt'+r][d] ,
t = parseInt( r ) + parseInt( s );
$('#subRadio').text( r + ' + ' );
$('#subDrop').text( s + ' = ' );
$('#total').text( t );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal text-left" id="meishi">
<div class="form-group">
<div class="col-lg-2 topic">
<label>Design</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" name="design" value="10800">op1
</label>
</div>
<div class="col-lg-4">
<label class="radio-inline">
<input type="radio" name="design" value="14040">op2
</label>
</div>
<div class="col-lg-3">
<label class="radio-inline">
<input type="radio" name="design" value="16200">op3
</label>
</div>
</div>
<div class="form-group">
<label class="col-lg-2" for="qtt">Quantity</label>
<select id="qtt" class="col-lg-3" name="qtt">
<option value="">Choose one</option>
<option value="a">100</option>
<option value="b">200</option>
<option value="c">300</option>
</select>
</div>
</form>
<span id="subRadio"></span>
<span id="subDrop"></span>
<span id="total"></span>

Try the working FIDDLE
Updated javascript
$(document).ready(function() {
function UpdatePrice() {
var CalMatrix = [{
val1: 10800,
val2: 'a',
resultant: 2160
}, {
val1: 10800,
val2: 'b',
resultant: 2484
}, {
val1: 10800,
val2: 'c',
resultant: 2808
},
{
val1: 14040,
val2: 'a',
resultant: 2808
}, {
val1: 14040,
val2: 'b',
resultant: 3132
}, {
val1: 14040,
val2: 'c',
resultant: 3456
},
{
val1: 16200,
val2: 'a',
resultant: 3240
}, {
val1: 16200,
val2: 'b',
resultant: 3564
}, {
val1: 16200,
val2: 'c',
resultant: 3888
}
];
var design = $('input[name=design]:checked').val();
var qtt = $("#qtt option:selected").val();
var result = $.grep(CalMatrix, function(n) {
return Number(n.val1) == Number(design) && n.val2 == qtt;
});
$('#subRadio').html('$ ' + String(result[0].val1))
$('#subDrop').html('$ ' + String(result[0].resultant))
$('#total').html('$ ' + parseInt(result[0].val1 + result[0].resultant, 10));
}
$('#qtt').on('change', function(e) {
UpdatePrice(); // to calculate the price on change event
});
UpdatePrice(); // to calculate the price on page load
});
Edit
Updated FIDDLE,
Attached a new handler on radio change event too
$('#qtt, input[type=radio][name=design]').on('change', function(e) {
UpdatePrice(); // to calculate the price on change event
});
Hope it works for you.

Related

How to bind an array to checkbox using Angular2 ReactiveFormsModule?

I am new to Angular2 (started yesterday) and not an Angular user before this. My question is how can I 2 way bind an array to checkbox in ReactiveFormsModule?
Below is my missing piece puzzle code.
<!-- profile.ts -->
export class UserProfileComponent {
status = {
ready: false,
saving: false
};
form: FormGroup;
masterData = {
skills: [{ id: 'js', text: 'Javascript' }, { id: 'cs', text: 'C#' }]
};
constructor(FB: FormBuilder) {
let self = this;
self.form = FB.group({
name: new FormControl('', Validators.required)
, gender: new FormControl('', Validators.required)
, skills: new FormArray([])
})
self.getProfile()
.then(profile => {
return self.loadFormData(profile);
}).then(() => {
this.status.ready = true
});
}
getProfile() {
return new Promise((done, fail) => {
let sample = { name: 'me', gender: 'm', skills: ['js']};
done(sample);
})
}
loadFormData({ name, gender, skills = []}) {
let self = this
, form = self.form
return new Promise((done, fail) => {
form.get('name').setValue(name);
form.get('gender').setValue(gender);
skills.reduce((array: FormArray, skill: string) => {
array.push(new FormControl(skill));
return array;
}, form.get('skills'));
done();
});
}
selectSkill (event, skill) {
let skills = this.form.get('skills')
, checked = event.target.checked
;
let index = skills.value.indexOf(skill);
if (checked === true && index < 0) {
skills.push(new FormControl(skill));
} else if (checked === false && index >= 0) {
skills.removeAt(index);
}
}
};
<!-- profile.html -->
<div class="title">Profile</div>
<div>
<form [formGroup]="form" (ngSubmit)="submitForm()">
<div class="form-group">
<label for="name">Name</label>
<input formControlName="name" name="name" class="form-control" placeholder="Name" type="text">
</div>
<div class="form-group">
<label>Gender</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="m" formControlName="gender"> Male</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="f" formControlName="gender"> Female</label>
</div>
<div class="form-group">
<label>Skill {{ skills }}</label>
</div>
<div *ngFor="let skill of masterData.skills">
<div class="checkbox-inline"><label>
<input type="checkbox" name="skill" (change)="selectSkill($event, skill.id)"> {{ skill.text }}
</label></div>
</div>
<div>
<button type="submit" class="btn" [disabled]="form.invalid">Save</button>
</div>
</form >
</div>
Everything work fine except I don't know how to make skills checkbox checked after form load based on my sample data?
You have to use FormArrayName directive :
// Compoenent
public allSkills = [
{ value : 'cs', label : 'C#' },
{ value : 'js', label : 'Javascript' }
];
constructor(FB: FormBuilder) {
this.form = FB.group({
name: new FormControl('', Validators.required),
gender: new FormControl('', Validators.required),
skills: new FormArray([])
});
for(let skill on this.allSkills) {
this.form.get('skills').push(new FormControl());
}
}
// HTML
<form [formGroup]="form" (ngSubmit)="submitForm()">
<div class="form-group">
<label for="name">Name</label>
<input formControlName="name" name="name" class="form-control" placeholder="Name" type="text">
</div>
<div class="form-group">
<label>Gender</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="m" formControlName="gender"> Male</label>
</div>
<div class="radio-inline">
<label><input type="radio" name="gender" value="f" formControlName="gender"> Female</label>
</div>
<div class="form-group">
<label>Skills</label>
</div>
<div formArrayName="skills">
<div class="checkbox-inline" *ngFor="let skill of skills.controls; let i=index">
<label>
<input type="checkbox" [formControlName]="i" [value]="allSkills[i]['value']"/> {{allSkills[i]['label']}}
</label>
</div>
</div>
<button type="submit" class="btn" [disabled]="form.invalid"> Save </button>
</form>

AngularJS - Conditionally hide a span

I want to hide the <span ng-show="currencyObject.to != 'undefined'">=</span> until the currencyObject.to is undefined which is supposed to be undefined until the user select an option from the select box.
I used ng-show="currencyObject.to != 'undefined'" to conditionally show-hide the span but it is not working. What I find is, when the page is freshly loaded, the = is visible.
<div class="row" ng-controller="QConvertController">
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="amount">Amount</label>
<input type="number" step="any" class="form-control" id="amount" ng-model="currencyObject.amount">
</div>
</div>
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="from">From</label>
<select class="form-control" id="from" ng-model="currencyObject.from" ng-change="getconvertedrate()">
<option ng-repeat="currencyCode in currencyCodes" value="{{currencyCode.value}}">{{currencyCode.display}}</option>
</select>
</div>
</div>
<div class="col-md-8 col-md-offset-2">
<div class="form-group">
<label for="to">To</label>
<select class="form-control" id="to" ng-model="currencyObject.to" ng-change="getconvertedrate()">
<option ng-repeat="currencyCode in currencyCodes" value="{{currencyCode.value}}">{{currencyCode.display}}</option>
</select>
</div>
</div>
<br>
<br>
<br>
<div class="col-md-8 col-md-offset-2">
<h1 class="display-4">{{currencyObject.amount}} {{currencyObject.from}} <span ng-show="currencyObject.to != 'undefined'">=</span> {{currencyObject.amount_converted}} {{currencyObject.to}}</h1>
</div>
</div>
QConvertController.js
var app = angular.module('qconvertctrlmodule', [])
.controller('QConvertController', function($scope, $http, $log) {
$scope.currencyObject = {};
$scope.currencyObject.from;
$scope.currencyObject.to;
$scope.currencyObject.amount;
$scope.currencyObject.amount_converted;
$scope.currencyObject.runCount = 0;
$scope.currencyCodes = [{value : 'INR', display : 'Indian Rupee'}, {value : 'USD', display : 'US Dollar'}, {value : 'GBP', display : 'British Pound'}];
$scope.getconvertedrate = function() {
$log.info("FROM : " + $scope.currencyObject.from);
$log.info("TO : " + $scope.currencyObject.to);
$http.get("http://api.decoded.cf/currency.php", {params : {from : $scope.currencyObject.from,
to : $scope.currencyObject.to, amount : $scope.currencyObject.amount}})
.then(function(response) {
$scope.currencyObject.amount_converted = response.data.amount_converted;
$log.info(response.data.amount_converted);
});
};
});
You don't need != 'undefined' to check the variable is defined or not
<span ng-show="currencyObject.to">=</span>
or
<span ng-hide="!currencyObject.to">=</span>
or
<span ng-if="currencyObject.to">=</span>
You can directly use as ng-show="currencyObject.to"
Also in Js correct usage of comparing with undefined is
if(typeof variable !== 'undefined'){ /*...*/ }

Multiple condition for dropdown list

I have this dropdown list
<label class="control-label">Type</label><br/>
<select class="form-control" ng-model="selectedItem" ng-change="selectChange()" ng-options="item as item.name for item in items">
<option value=""> Select Type</option>
</select>
this is the list in items.
$dialogScope.items = [{
name:"Pencil",
value:"0",
},{
name:"Eraser",
value:"1"
},{
name:"Colourpencil",
value:"2",
},{
name:"Ruler",
value:"4",
},{
name: "Pen",
options : ["Blue","Red","Colourful"]
},{
name: "Laptop",
options : ["Dell","Lenovo","Acer"]
},{
name: "Pencil Box",
value:"7",
},{
name: "Download CACHE By GPU",
value:"8",
},
];
What is want is that if user choose Pencil or Eraser or Ruler or Pencil Box, label A and Label B field will hide. I tried as below
<div class="form-group has-feedback" ng-if="type==0||type==1||type==4||type==7" ng-hide="hideField1">
<label class="control-label">{{labelA}}</label>
<input type="url" class="form-control" ng-model="stepA" name="stepA" required>
</div>
<div class="form-group has-feedback" ng-if="type==5||type==6||type==8||type==10" ng-hide="hideField2">
<label class="control-label">{{labelB}}</label>
<input type="url" class="form-control" ng-model="stepB" name="stepB" required>
</div>
<div class="form-group has-feedback" ng-if="type==0||type==4||type==7||type==5||type==6||type==8||type==9||type==10" ng-hide="hideField3">
<label class="control-label">{{labelC}}</label>
<input type="text" class="form-control" ng-model="stepC" name="stepC" required>
</div>
And use this in the controller but it doesn't to be in the right way. Anyone notice the mistake? and if any correct way to create this.
UPDATED
$dialogScope.selectChange = function(selectedItem){
if (selectedItem) {
$dialogScope.type = selectedItem.value;
$dialogScope.labelA = '';
$dialogScope.labelB = '';
$dialogScope.labelC = 'MD5';
$dialogScope.stepA = '';
$dialogScope.stepB = '';
$dialogScope.stepC = '';
if ($dialogScope.value == 0) {
$dialogScope.labelA = "APK URL";
} else if ($dialogScope.value == 4) {
$dialogScope.labelA = "OBB URL";
} else if ($dialogScope.value == 5) {
$dialogScope.labelB = "OBB URL";
} else if ($dialogScope.value == 6) {
$dialogScope.labelB = "APK URL";
}
console.log($dialogScope.selectedItem)
};
Check out this
var jimApp = angular.module("mainApp", []);
jimApp.controller('mainCtrl', function($scope){
$scope.items = [{
name:"Pencil",
value:"0",
},{
name:"Eraser",
value:"1"
},{
name:"Colourpencil",
value:"2",
},{
name:"Ruler",
value:"4",
},{
name: "Pen",
options : ["Blue","Red","Colourful"]
},{
name: "Laptop",
options : ["Dell","Lenovo","Acer"]
},{
name: "Pencil Box",
value:"7",
},{
name: "Download CACHE By GPU",
value:"8",
},
];
$scope.hideMe = function(hideElements){
if($scope.selectedItem){
return (hideElements.indexOf($scope.selectedItem.name) != -1)?true:false;
}
else{
return true;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="mainApp" ng-controller="mainCtrl">
<label class="control-label">Type</label><br/>
<select class="form-control" ng-model="selectedItem" ng-change="selectChange()" ng-options="item as item.name for item in items">
<option value=""> Select Type</option>
</select>
{{selectedItem}}
<div class="form-group has-feedback" ng-if="selectedItem && hideMe(['Pencil', 'Ruler']);">
<label class="control-label">{{(selectedItem.value==0)?"APK URL":"OBB URL"}}</label>
<input type="url" class="form-control" ng-model="stepA" name="stepA" required>
</div>
<div class="form-group has-feedback" ng-if="selectedItem && hideMe(['Pen', 'Laptop']);">
<label class="control-label">{{(selectedItem.value==5)?"OBB URL":"APK URL"}}</label>
<input type="url" class="form-control" ng-model="stepB" name="stepB" required>
</div>
<div class="form-group has-feedback">
<label class="control-label">labelC</label>
<input type="text" class="form-control" ng-model="stepC" name="stepC" required>
</div>
</div>

How can i check radio button by default?

On page load i want to show below radio button selected by default i used html attribute but its not working. So on page load I want to show all process radio button checked by default. Is there any other way to achieve this task?
radio.html
<div class="panel panel-default">
<div class="panel-heading">View/Search Inventory</div>
<div class="panel-body">
<div class="row">
<div class="col-md-2">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterOptions"
k-ng-model="kfilter" ng-model="filter" ng-change="onChange()"></select>
</div>
<div ng-show="filter=='PROCESS'" ng-init="search.showCriteria='allProcess';onChange()">
<div class="col-md-7">
<label class="radio-inline" for="allProcess"> <input
type="radio" name="optionsRadios1" ng-value="'allProcess'"
id="allProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show All Processes
</label> <label class="radio-inline" for="ratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'ratedProcess'"
id="ratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Rated Processes
</label> <label class="radio-inline" for="unratedProcess"> <input
type="radio" name="optionsRadios1" ng-value="'unratedProcess'"
id="unratedProcess" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unrated Processes
</label>
</div>
</div>
<div ng-show="filter=='RISK'">
<div class="col-md-7">
<label class="radio-inline" for="allRisk"> <input
type="radio" name="optionsRadios1" ng-value="'allRisk'"
id="allRisk" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Risks
</label> <label class="radio-inline"> <input type="radio"
name="optionsRadios1" ng-value="'unalignedRisk'"
ng-model="search.showCriteria" ng-change="selectSearchType()">
Show Unaligned Risks
</label>
</div>
</div>
<div ng-show="filter=='CONTROL'">
<div class="col-md-7">
<label class="radio-inline" for="allControl"> <input
type="radio" name="optionsRadios1" ng-value="'allControl'"
id="allControl" ng-model="search.showCriteria" ng-checked="true"
ng-change="selectSearchType()"> Show All Controls
</label> <label class="radio-inline" for="unalignedControl"> <input
type="radio" name="optionsRadios1" ng-value="'unalignedControl'"
id="unalignedControl" ng-model="search.showCriteria"
ng-change="selectSearchType()"> Show Unaligned Controls
</label>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-default" type="button" ng-click="search(0)">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</div>
</div>
<div class="row">
<!--<label for="filterBy" class="col-md-1">Filter by: </label>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'" k-option-label="'Select'"
k-data-value-field="'value'" k-data-source="filterByOptions"
k-ng-model="kfilterBy" ng-model="filterBy" style="width: 100%"></select>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-data-value-field="'value'" k-data-source="filterByValues" k-option-label="'Select'"
k-ng-model="kfilterByValue" ng-model="filterByValue" style="width: 100%"></select>
</div> -->
<div class="col-md-3">
<a href="" ng-show="!showAdvance" ng-click="advanceFilter()">Advanced
Search</a> <a href="" ng-show="showAdvance" ng-click="advanceFilter()">Basic
Search</a>
<!-- <button ng-show="!showAdvance" class="btn btn-default" type="button" ng-click="search()">Go</button> -->
</div>
</div>
<form role="form" name="formTimeLine" kendo-validator="validator"
k-options="myValidatorOptions">
<div ng-show="showAdvance">
<div class="clone" ng-repeat="input in inputs">
<br />
<div class="row">
<div class="col-md-1">
<a ng-if="inputs.length < searchOptions.length"
class="add col-md-1" name="addnumadd" ng-click="add($index)"> </a>
<a ng-if="inputs.length >1" class="delete col-md-1"
name="deletenumadd" ng-click="remove($index)"> </a>
</div>
<div class="col-md-3">
<select kendo-drop-down-list k-data-text-field="'name'"
k-option-label="'Select'" k-data-value-field="'value'"
k-data-source="searchOptions" name="searchBy-{{$index}}"
ng-model="input.searchBy"
data-required-msg="Please select the value"
ng-change="clearPreviousValue({{$index}})" data-duplicate=""
style="width: 100%" required></select>
</div>
<div class="col-md-3">
<input type="text" class="form-control"
ng-model="input.searchValue" placeholder="Enter search item"
ng-maxlength="256" name={{$index}}>
</div>
<div class="col-md-4">
<input type="radio" name={{$index}} value="exactMatch"
ng-model="input.exactMatch" data-requiredCheckbox=""> Exact
Match <input type="radio" name={{$index}} value="contains"
ng-model="input.exactMatch" data-requiredCheckbox=""> Contains
<span class="k-invalid-msg" data-for={{$index}}></span>
</div>
</div>
</div>
</div>
</form>
</div>
<div id="outergrid" class="row">
<ng-include src="gridInclude"></ng-include>
</div>
</div>
radio.js
$scope.processSearchOptions = processSearchOptions;
$scope.riskSearchOptions = riskSearchOptions;
$scope.controlSearchOptions = controlSearchOptions;
$scope.filterByOptions = filterByOptions;
$scope.filterByValues = filterByValues;
$scope.searchOptions = processSearchOptions;
$scope.onChange = function () {
var value = $scope.filter;
$scope.postArgs.page = 1;
if (value === 'PROCESS') {
$scope.search.showCriteria = 'allProcess';
$scope.searchOptions = processSearchOptions;
$scope.gridInclude = 'views/viewAll/processGrid.html';
}
if (value === 'RISK') {
$scope.search.showCriteria = 'allRisk';
$scope.searchOptions = riskSearchOptions;
$scope.gridInclude = 'views/viewAll/riskGrid.html';
}
if (value === 'CONTROL') {
$scope.search.showCriteria = 'allControl';
$scope.searchOptions = controlSearchOptions;
$scope.gridInclude = 'views/viewAll/controlGrid.html';
}
$scope.showAdvance = false;
$scope.clearAdvFilter();
$scope.postArgs = {
page: 1
};
};
//initialize process grid
initializeGrid('process');
$scope.processGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.processGridColumns);
$scope.processInnerGridOptions = viewSearchInvService.getInnerProcessGrid;
//initialize risk grid
initializeGrid('risk');
$scope.riskGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.riskGridColumns);
$scope.riskInnerGridOptions = viewSearchInvService.getInnerRiskGrid;
//initialize control grid
initializeGrid('control');
$scope.controlGridOptions = getProcessGridOptions($scope.postArgs, gridColumns.controlGridColumns);
$scope.controlInnerGridOptions = viewSearchInvService.getInnerControlGrid;
$scope.ProcessEditHandler = function (id) {
ViewEditPrcsService.saveProcessId(id);
};
$scope.RiskEditHandler = function (id) {
ViewEditRiskService.saveRiskId(id);
};
$scope.advanceFilter = function () {
if ($scope.showAdvance) {
$scope.clearAdvFilter();
$scope.showAdvance = false;
} else {
$scope.showAdvance = true;
}
};
$scope.clearAdvFilter = function () {
$scope.inputs = [];
$scope.inputs.push(getNewObject());
};
$scope.search = function () {
if ($scope.validator.validate() || !$scope.showAdvance) {
searchCriteria(1);
searchFlag = true;
if ($scope.filter === 'PROCESS') {
$scope.search.process.dataSource.read();
}
if ($scope.filter === 'RISK') {
$scope.search.risk.dataSource.read();
}
if ($scope.filter === 'CONTROL') {
$scope.search.control.dataSource.read();
}
}
};
$scope.selectSearchType = function () {
$scope.clearAdvFilter();
$scope.showAdvance = false;
$scope.search();
};
$scope.add = function () {
$scope.inputs.push(getNewObject());
};
$scope.remove = function (index) {
$scope.inputs.splice(index, 1);
};
$scope.myValidatorOptions = {
rules: {
duplicate: function (input) {
return checkDuplicates(input.val(), input[0].name);
},
requiredCheckbox: function (input) {
return !(input[0].type === 'radio' && !$scope.inputs[input[0].name].exactMatch && !$scope.inputs[input[0].name].contains);
}
},
messages: {
duplicate: 'Option already selected. please select another option',
requiredCheckbox: 'Operator is required'
}
};
$scope.clearPreviousValue = function (index) {
$scope.inputs[index].searchValue = '';
};
});
Without knowing more about the specifics of when you want this checked, apply the following using ngChecked. In this case, checked if true, but this can be any expression
ng-checked="true"
JSFiddle Link
In response to your updated code, you could leverage ngInit on your parent <div> for defaulting one radio button in a group. Note for isolating the direct issue I have slimmed down most of this markup
<div ng-init="search.showCriteria='allProcess'">
Updated JSFiddle Link
You need to make sure your model is set to the value of the radio box.
$scope.search.showCriteria = 'allProcess'
As a side node, you don't need to be using ng-value here. You could use just use value="allProcess" because ng-value is only needed for Angular expressions, not plain strings.

angularjs filter: ng-options removing duplicates

Is there a way to remove duplicated values from a option field in angularjs when you are getting data from a json.
For ex: I have many json objects like this
{
productCat: "G"
productCatDesc: "GENERAL"
productCode: "1"
productDes: "LOCAL"
subproductCode: "10"
}
{
productCat: "G"
productCatDesc: "GENERAL"
productCode: "1"
productDes: "FOREIGN"
subproductCode: "10"
}
{
productCat: "G"
productCatDesc: "RELIGION"
productCode: "1"
productDes: "GEN"
subproductCode: "10"
}
{
productCat: "G"
productCatDesc: "RELIGION"
productCode: "1"
productDes: "REL"
subproductCode: "10"
}
NOTE: there are many objects like these.My task is to show 'productDes's according to the 'productCatDesc' . I have hardcoded 'productCatDesc'.SO for ex: if i choose General from the selection option i have to show the 'productDes' according to it.But the way i have done it 'productDes' is read from every object resulting repeating data.I only want to show only the 2types (Local,Foreign).How can i achieve this?
This is what i have so far
$scope.productList = function(){
if($scope.user.productCat.name.localeCompare("GENERAL")==0){
window.alert("genData");
// $scope.productListArr = $scope.generalData;
for(var k=0; k<$scope.generalData.length ; k++){
$scope.productListArr[0] = $scope.generalData[0];
var arrayObject = $scope.generalData[k];
if($scope.productListArr[k].productDes.localeCompare(arrayObject.productDes) != 0){
$scope.productListArr.push(arrayObject);
}
}
} else {
window.alert("IslData");
$scope.productListArr = $scope.islamicData;
for(var k =0; k< $scope.productListArr.length ;k++){
var arrayObj = $scope.productListArr[k];
if ($scope.filteredProductArray.indexOf(arrayObj.productDes) == -1) {
$scope.filteredProductArray.push(arrayObj);
}
}
window.alert("here");
window.alert(filteredProductArray.length);
}
};
My HTML
<div class="form-group" ng-class="{ 'has-error' :submitted && (userForm.productCat.$pristine || thirdPartyForm.productCat.$invalid)}">
<label class="labelColor"><h5><b>Product Category</b></h5></label>
<select id="productCat" name="productCat" style="margin: auto; width:100%; " ng-model="user.productCat" ng-options="cat.name for cat in productCatList" ng-disabled="isDisabled" required>
<option value="" selected="selected">--Select Type--</option>
<optgroup label="user.productCat.name"></optgroup>
</select><br>
<span class="help-inline" ng-show="submitted && (userForm.productCat.$pristine || userForm.productCat.$invalid)" >A Product Category is required.</span>
</div>
<toaster-container toaster-options="{'note': 3000, 'close-button':true}"></toaster-container>
<!--Product-->
<div class="form-group" ng-class="{ 'has-error' :submitted && (userForm.product.$pristine || thirdPartyForm.product.$invalid)}">
<label class="labelColor"><h5><b>Product</b></h5></label>
<select id="product" name="product" style="margin: auto; width:100%; " ng-model="user.product" ng-options="prod.name for prod in productList" ng-disabled="isDisabled" required>
<option value="" selected="selected">--Select Type--</option>
<optgroup label="user.product.name"></optgroup>
</select><br>
<span class="help-inline" ng-show="submitted && (userForm.product.$pristine || userForm.product.$invalid)" >A Product is required.</span>
</div>
<!--Sub Product-->
<div class="form-group" ng-class="{ 'has-error' :submitted && (userForm.Subproduct.$pristine || thirdPartyForm.Subproduct.$invalid)}">
<label class="labelColor"><h5><b>Sub Product</b></h5></label>
<select id="Subproduct" name="Subproduct" style="margin: auto; width:100%; " ng-model="user.Subproduct" ng-options="Subprod.name for Subprod in SubproductList" ng-disabled="isDisabled" required>
<option value="" selected="selected">--Select Type--</option>
<optgroup label="user.Subproduct.name"></optgroup>
</select><br>
<span class="help-inline" ng-show="submitted && (userForm.Subproduct.$pristine || userForm.Subproduct.$invalid)" >A Sub Product is required.</span>
</div>
<!-- BUTTONS -->
<div class="col"style="text-align: center">
<button align="left"class="button button-block button-reset"style="display: inline-block;width:100px;text-align:center "
type="reset"
ng-click="submitted = false; reset();" padding-top="true">Reset</button>
<button class="button button-block button-positive" style="display: inline-block;width:100px "
ng-click="submitted=true; "padding-top="true">Submit</button>
</div>

Categories