Multiple condition for dropdown list - javascript

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>

Related

Submitting angular form to a php file [duplicate]

This question already has answers here:
How do I POST urlencoded form data with $http without jQuery?
(11 answers)
Closed 6 years ago.
I'm trying to submit the form below to a php file called time.php, but its not working, even when I check the console there are no errors, its just clear. I'm not sure where I may be going wrong.
<form ng-controller="testCtrl" class="customform" data-ng-init="init()">
<div class="s-10 1-10">
<input ng-model="firstName" pattern=".{2,100}" title="2 to 100 Characters" placeholder="First Name" type="text" required />
</div>
<div class="s-10 1-10">
<input ng-model="lastName" pattern=".{5,255}" title="5 to 255 Characters" placeholder="Last Name" type="text" required />
</div>
<div class="s-12 l-10"><input ng-model="acNumber" placeholder="A/C Number" title="Employee Number, i.e c1234567" type="text" required /></div>
<div class="s-12 l-10"><input ng-model="email" placeholder="Email" title="Email" type="email" required /></div>
<div class="s-12 l-10">
<select ng-model="selectedRequestType" ng-options="requestType as requestType.type for requestType in requestTypes" required="required">
<option value="" disabled selected>Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedWorkRequestType" ng-options="workRequestType as workRequestType.type for workRequestType in workRequestTypes">
<option value="" disabled selected>Work Request Type</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedFile" ng-options="file as file.type for file in files">
<option value="" disabled selected>Files</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'New file(s) from source'" ng-model="selectedLibrary" ng-options="library as library.type for library in libraries">
<option value="" disabled selected>Does Library Exist</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedWorkRequestType.type == 'Code Automation' || selectedWorkRequestType.type == 'Amendments to existing code'" ng-model="selectedOutput" ng-options="outputType as outputType.type for outputType in outputTypes">
<option value="" disabled selected>Output</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedLibrary.type == 'Yes' || selectedRequestType.type == 'Incident'" ng-model="selectedPlatformOutput" ng-options="platformOutput as platformOutput.type for platformOutput in platformOutputs">
<option value="" disabled selected>Platform Output</option>
</select>
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAS' || selectedPlatformOutput.type =='SAS'" ng-model="sasLibraryName" type="text" placeholder="SAS Library Name: SPDS Exploit" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'SAP IQ' || selectedPlatformOutput.type =='SAP IQ'" ng-model="sapIQtext" placeholder="SAP IQ" >
</div>
<div class="s-12 l-10">
<input ng-show="selectedOutput.type == 'Hadoop' || selectedPlatformOutput.type =='Hadoop'" placeholder="Library Name: HDFS_Exploit" ng-model="hadoop" />
</div>
<div class="s-12 l-10">
<input ng-show="selectedWorkRequestType.type == 'Amendments to existing code'" placeholder="Output Dataset Name" ng-model="outputDataset" type="text"/>
</div>
<div class="s-12 l-10">
<input ng-show="selectedLibrary.type == 'No'" type="text" ng-model="productName" Placeholder="Product Name" />
</div>
<div class="s-12 l-10">
<input ng-show="" placeholder="Upload Text File" type="file" ng-model="uploadTextFile" title="Please upload a txt file with the layout - to " multiple />
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" type="text" ng-model="tableName" placeholder="Dataset/Table Name" />
</div>
<div class="s-12 l-10">
<textarea placeholder="Special Instructions" ng-model="specialInstruction" rows="5"></textarea>
</div>
<div class="s-12 l-10">
<input ng-show="selectedRequestType.type == 'Incident'" ng-model="uploadScreenshot" placeholder="Upload Screenshot of error" type="file" multiple/>
</div>
<div class="s-12 l-10">
<select ng-show="selectedRequestType.type == 'Work Request'" ng-model="selectedFrequency" ng-options ="frequency as frequency.type for frequency in frequencies">
<option value="" disabled selected>Frequency</option>
</select>
</div>
<div class="s-12 l-10">
<select ng-show="selectedFrequency.type == 'Weekly'" ng-model="selectedWeekly" ng-options ="weekly as weekly.type for weekly in weeklies">
<option value="" disabled selected>Weekly Frequency</option>
</select>
</div>
<input type="hidden" ng-model="token" value="<?php echo Token::generate()?>">
<div class="s-4"><button type="submit" id="submit" class="btn-custom btn btn-large btn-block" ng-click="sendRequest()">Request</button></div>
Please note: ng-app="app" is located in the header:
<!DOCTYPE html>
<html lang="en-US" ng-app="app">
The following code is the controller, and I believe the issue lies somewhere in here:
var app = angular.module('app', []);
app.controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.sendRequest = function(){
var data= {
'firstName' :$scope.firstName,
'lastName' :$scope.lastName,
'acNumber' :$scope.acNumber,
'email' :$scope.email,
'selectedRequestType' :$scope.selectedRequestType,
'selectedWorkRequestType' :$scope.selectedWorkRequestType,
'selectedOutput' :$scope.selectedOutput,
'selectedFrequency' : $scope.selectedFrequency,
'selectedWeekly' : $scope.selectedWeekly,
'selectedFile' : $scope.selectedFile,
'selectedLibrary' : $scope.selectedLibrary,
'selectedPlatformOutput' : $scope.selectedPlatformOutput,
'productName' : $scope.productName
};
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).success(function(data, status, headers, config) {
//Success code
}).error(function(xhr) {
//Failure code
console.log(data);
console.log(xhr.responseText);
});
return false;
// $window.location.href ='/time.php';
};
$scope.init = function (){
$scope.workRequestType = 'test';
$scope.requestTypes = [
{'type':'Work Request'},
{'type': 'Incident'}
];
$scope.workRequestTypes = [
{'type': 'Amendments to existing code'},
{'type': 'Code Automation'},
{'type': 'New file(s) from source'}
];
$scope.outputTypes = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.frequencies = [
{'type' : 'Daily'},
{'type': 'Monthly'},
{'type': 'Weekly'}
];
$scope.weeklies = [
{'type': 'Monday'},
{'type':'Tuesday'},
{'type': 'Wednesday'},
{'type':'Thursday'},
{'type':'Friday'},
{'type':'Saturday'},
{'type':'Sunday'}
];
$scope.files = [
{'type': 'New File(s)'},
{'type': 'Add to existing file received'}
];
$scope.libraries = [
{'type':'Yes'},
{'type':'No'}
];
$scope.platformOutputs = [
{'type': 'SAS'},
{'type':'SAP IQ'},
{'type': 'Hadoop'}
];
$scope.firstName= null;
$scope.lastName= null;
$scope.acNumber= null;
$scope.email= null;
$scope.selectedRequestType= null;
$scope.selectedWorkRequestType= null;
$scope.selectedOutput= null;
$scope.sasLibraryName = null;
$scope.sasIQtext = null;
$scope.selectedFrequency = null;
$scope.selectedWeekly = null;
$scope.selectedFile = null;
$scope.selectedLibrary = null;
$scope.selectedPlatformOutput = null;
$scope.productName = null;
};
}]);
I'm still learning Angular, so I may have made a simple error
If the HTTP POST request is taking place, but PHP is not able to access the POST variables, try converting the data from an object to a string.
$http({
url: "time.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike(data),
})
The string should look like: firstName=John&acNumber=1234
Pass the $httpParamSerializerJQLike service into your controller with:
app.controller('testCtrl', ['$scope', '$http', '$httpParamSerializerJQLike', function($scope, $http, $httpParamSerializerJQLike) {

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'){ /*...*/ }

how to display selected value of dropdown in input text fields in angular js

html file:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
js file:
if (data){
console.log(data);
$scope.addressToShip = data;
var ShipAddress=[];
storeLocally.set('ship Info', data);
if(data.addressLine2 == null){
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else{
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
},
function (data) {
//if (data.status == 500) {
// $scope.addressError = "Oops! No Address Found!";
};
data:
{0 :"123 waller st,suite#220"},
{1 :"323 waller st,suite#230"}
The problem is the form I am using intially to save data. Once data is saved to db it is coming in dropdown. After choosing one value from dropdown it should come to text fields.
I have tried so far ng-model by using same variable names,even though form's ng-model and dropdown's ng-model have same variable i.e. shipping.. But it didn't work. Please help me out what I am missing in here.
If I understand your goal and you data's schema, you need to change the ng-model of the input[name="Address"] to shipping.addressLine1.shipping.
I get this idea according the data's structure that came from the .map:
return {
shipping: address.addressLine1
};
You can see the structure when you pick a option from the select - the model will displayd and you can see that the structure is (for example):
{
"addressLine1": {
"shipping": "123 waller st"
}
}
If you have a question about this, let me know.
I tried to simulate the situation without the server, hopefully I simulate it right.
Now, to the code:
angular.module('myApp', []).
controller('ctrl', function($scope) {
var data = [{
addressLine1:"123 waller st", addressLine2:"suite#220"
}];
if (data) {
console.log(data);
$scope.addressToShip = data;
var ShipAddress = [];
//storeLocally.set('ship Info', data);
if (data.addressLine2 == null) {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1
};
});
}
else {
$scope.shipAddress = data.map(function(address) {
return {
shipping: address.addressLine1 +', '+ address.addressLine2
};
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
<select ng-model="shipping.addressLine1" ng-options="shipping.shipping for shipping in shipAddress">
<option value=''>--Select Address --</option>
</select>
<br />
<pre>
{{shipping | json}}<br />
{{shipping.addressLine1 | json}}
</pre>
<form name="shippingForm" class="form-horizontal" role="form">
<div class="form-group">
<p class="control-p col-sm-2" for="Address">Address Line1</p>
<div class="col-sm-10">
<input type="text" name="Address" placeholder="Address Line1"
ng-model="shipping.addressLine1.shipping" class="input-width" ng-init ="shipping.addressLine1"/>
</div>
</div>
<div class="form-group">
<p class="control-p col-sm-2" for="Address2">Address Line2:</p>
<div class="col-sm-10">
<input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
</div>
</div>
</form>
</div>
Did you try using AngularJS' ng-change attribute in the drop down?
Try like this:
<select ng-model="shipping" ng-options="shipping.shipping for shipping in shipAddress" ng-change="someFunction(shipping.shipping)">
<option value=''>--Select Address--</option>
</select>
In your controller add the following function:
$scope.someFunction = function(shipping) {
$scope.shipping.addressLine1 = // Assign value from the shipping variable here
$scope.shipping.addressLine2 = // Assign value from the shipping variable here
}
Hope this helps!
Here is a working jsFiddle https://jsfiddle.net/ashishU/umn8or3g/1/

How can I get cascading dropdown at level 4?

Here is my attempt:
If the user hits Territory A i need to display "Sales Team A" and "Sales Team B" as my options.`enter code here: http://plnkr.co/edit/n2A83tHk4r0G1ZWddb7V?p=preview.
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div data-ng-app="myApp" class="container">
<form class="form-horizontal" data-ng-controller="dropdownCtrl">
<div class="form-group">
<label for="country" class="col-sm-2 control-label">* </label>
<div class="col-sm-7">
<select data-ng-model="customer.Country"
data-ng-options="obj.id as obj.country for obj in countries"
data-ng-change="getCountryStates()"
class="form-control"
data-ng-required="true"
id="country">
<option value="">-- Choose Org --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="state" class="col-sm-2 control-label">** </label>
<div class="col-sm-7">
<select data-ng-model="customer.State"
data-ng-options="x.Id as x.state for x in sates"
data-ng-change = "getStateCities()"
class="form-control"
data-ng-required="true"
id="state">
<option value="">-- Select --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="city" class="col-sm-2 control-label">*** </label>
<div class="col-sm-7">
<select data-ng-model="customer.City"
data-ng-options="x.Id as x.city for x in cities"
data-ng-change = "getStatesSales()"
class="form-control"
data-ng-required="true"
id="city">
<option value="">-- Select --</option>
</select>
</div>
</div>
<div class="form-group">
<label for="sales" class="col-sm-2 control-label">**** </label>
<div class="col-sm-7">
<select data-ng-model="customer.Sales"
data-ng-options="x.Id as x.sales for x in mysales"
class="form-control"
data-ng-required="true"
id="sales">
<option value="">-- Select --</option>
</select>
</div>
</div>
</form>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Here is my index.js file:
var myApp = angular.module('myApp',[]);
myApp.controller('dropdownCtrl', ['$scope','CustomerService', function($scope, CustomerService) {
$scope.countries = CustomerService.getCountry();
$scope.getCountryStates = function(){
$scope.sates = CustomerService.getCountryState($scope.customer.Country);
$scope.cities =[];
$scope.mysales = [];
}
$scope.getStateCities = function(){
// debugger;
$scope.cities = CustomerService.getStateCity($scope.customer.State);
console.log("Hi");
// console.log($scope.cities);
}
$scope.getStatesSales = function(){
// debugger;
$scope.sales = CustomerService.getSalesList($scope.customer.Sales);
// console.log($scope.sales);
}
}]);
myApp.factory("CustomerService", ['$filter', function($filter){
var service = {};
var countrylist = [
{ "id": 1, "country": "Marketing" },
{ "id": 2, "country": "Sales" },
{ "id": 3, "country": "Customer Service" }
];
var statelist = [
{"Id":1, "state":"Marketing Team A", "countryId": 1},
{"Id":3, "state":"Marketing Team B", "countryId": 1},
{"Id":4, "state":"Territories", "countryId": 2}
];
var citylist = [
{"Id":5, "city":"Territory A", "stateId": 4},
{"Id":6, "city":"Territory B", "stateId": 4}
];
var salesTeamList = [
{"Id":1, "sales":"Sales Team A", "salesId": 5},
{"Id":2, "sales":"Sales Team B", "salesId": 5},
{"Id":3, "sales":"Sales Team A", "salesId": 6},
{"Id":4, "sales":"Sales Team B", "salesId": 6}
];
service.getCountry = function(){
return countrylist;
};
service.getCountryState = function(countryId){
var states = ($filter('filter')(statelist, {countryId: countryId}));
return states;
};
service.getStateCity = function(stateId){
var items = ($filter('filter')(citylist, {stateId: stateId}));
return items;
};
service.getSalesList = function(salesId){
var items = ($filter('filter')(salesTeamList, {salesId: salesId}));
return items;
console.log(items);
};
return service;
}]);
You missed two points:
I changed here the parameter to $scope.customer.City
$scope.getStatesSales = function(){
$scope.sales = CustomerService.getSalesList($scope.customer.City);
}
and in your last drop down you passed the wrong list mySales so I changed it to sales in ng-repeat
data-ng-options="x.Id as x.sales for x in sales"
See the plunker

Javascript/Jquery - Calculate values and show inside a div

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.

Categories