Disable optgroup of multiple select which has specific label - javascript

I have taken a select list with multiple option using ng-options. I am using it as below:
<select ng-options="c as c.Text for c in ReceiverList track by c.Value" ng-model="ReceiverUserID" class="form-control" id="ddlReceiverUserID" ng-change="GetWorkers(ReceiverUserID, SenderUserID,'receiver')">
<option value="">--Select Supervisor--</option>
</select> <!-- Parent Drop Down-->
<select multiple ng-options="c as c.Text group by c.Group
for c in receiveList track by c.Value" ng-model="Workers"
class="form-control" id="ddlWorkers" size="10">
</select> <!-- Child Drop Down -->
This select dropdown get filled when I select some item from another dropdown.(It's a kind of cascaded dropdown). Filling it like below:
$scope.GetWorkers = function (objA, objB, ddlType) {
$http.post("user/Workers/", { userID: objA.Value })
.success(function (data, status, headers, config) {
if (ddlType == 'sender') {
$scope.sendList = data;
} else {
$scope.receiveList = data;
$('#ddlWorkers optgroup[label="Current Users"] option').prop('disabled', true); // Not working
}
})
.error(function (data, status, headers, config) {
showToast(ToastType.error, "Error occured while fetching workers.", "Failure");
});
}
I want to disable child dropdown's specific group items. So I tried below code but it is not working:
$('#ddlWorkers optgroup[label="Current Users"] option').prop('disabled', true);
I don't know how do I disable specific group items of select whenever its data changes or new data loaded.
Here is HTML output in which I want to disable all optgroup[label="Current Users"] members:
<select multiple="" ng-options="c as c.Text group by c.Group for c in receiveList track by c.Value" ng-model="Workers" class="form-control ng-pristine ng-valid" id="ddlWorkers" size="10">
<optgroup label="Current Users">
<option value="4118">Kevins Numen</option>
<option value="4119">ggdfg fdgdfg</option>
</optgroup>
<optgroup label="New Users">
<option value="1093">Case Worker</option>
</optgroup>
</select>

I don't know much about angularjs or ng-options, but it seems that everybody else used some timeout to let the process populate the received data to the input, and you can try something this like others:
...
} else {
$scope.receiveList = data;
setTimeout(function(){
$('#ddlWorkers optgroup[label="Current Users"] option')
.prop('disabled', true); // Not working
}, 100);
}
...
maybe not similar but good to have a look here:
is there a post render callback for Angular JS directive?

You need to customize your code and also JSON Object
<div ng-controller="AjaxCtrl">
<h1>AJAX - Oriented</h1>
<div>
Country:
<select id="country" ng-model="country" ng-options="country for country in countries">
<option value=''>Select</option>
</select>
</div>
<div>
City: <select id="city" ng-disabled="!cities" ng-model="city"><option value='' ng-repeat="item in cities" ng-disabled="item.disabled">{{item.name}}</option></select>
</div>
<div>
Suburb: <select id="suburb" ng-disabled="!suburbs" ng-model="suburb" ng-options="suburb for suburb in suburbs"><option value='' ng-disabled="item.disabled" ></option></select>
</div>
</div>
Your Angular
function AjaxCtrl($scope) {
$scope.countries = ['usa', 'canada', 'mexico', 'france'];
$scope.$watch('country', function(newVal) {
if (newVal)
$scope.cities = [
{ id: 1, name: '11111'},
{ id: 2, name: '22222', disabled: true },
{ id: 3, name: '33333', disabled: true }
]
});
$scope.$watch('city', function(newVal) {
if (newVal) $scope.suburbs = ['SOMA', 'Richmond', 'Sunset'];
});
}
function AjaxCtrl($scope) {
$scope.countries = ['usa', 'canada', 'mexico', 'france'];
$scope.$watch('country', function(newVal) {
if (newVal)
$scope.cities = [
{ id: 1, name: '11111'},
{ id: 2, name: '22222', disabled: true },
{ id: 3, name: '33333', disabled: true }
]
});
$scope.$watch('city', function(newVal) {
if (newVal) $scope.suburbs = ['SOMA', 'Richmond', 'Sunset'];
});
}
<link href="http://fiddle.jshell.net/css/normalize.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<div ng-controller="AjaxCtrl" class="ng-scope">
<h1>AJAX - Oriented</h1>
<div>
Country:
<select id="country" ng-model="country" ng-options="country for country in countries" class="ng-valid ng-dirty"><option value="" class="">Select</option><option value="0">usa</option><option value="1">canada</option><option value="2">mexico</option><option value="3">france</option></select>
</div>
<div>
City: <select id="city" ng-disabled="!cities" ng-model="city" class="ng-valid ng-dirty"><!-- ngRepeat: item in cities --><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding">11111</option><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding" disabled="disabled">22222</option><option value="" ng-repeat="item in cities" ng-disabled="item.disabled" class="ng-scope ng-binding" disabled="disabled">33333</option></select>
</div>
<div>
Suburb: <select id="suburb" ng-disabled="!suburbs" ng-model="suburb" ng-options="suburb for suburb in suburbs" class="ng-pristine ng-valid" disabled="disabled"><option value="" ng-disabled="item.disabled" class=""></option></select>
</div>
</div>
Reference

Related

Dynamically generate nested inputs in form

I'm very new into frontend, so I appreciate any help.
I'm trying to build a form, where user select an option from element and then depending on condition, dynamically generates another one (and some other inputs) as a child elements.
Finally what I'm trying to get is JSON with nested structure. E.g.
fields: [{type: 'List', value: [{type: 'Map', value: [{type: 'Integer', value: 5}, {type: 'List', value: [and so on...]]]}]
I have already started to code it in native JS and this is what I have so far (snippet below).
I want to release something similar with VUE.js library (or maybe someone can tell me any other useful libraries), cuz I want to control visibility of my inputs based on some conditions and some other useful features...but I dont know how to dynamically push elements into nested into nested and so on...I appriciate any help, any ideas and any examples. Thanks!
let template = `
<select name="type" onChange="createChildElement(this)" aria-label="Select type">
<option value="List">Select type</option>
<option value="List">List</option>
<option value="Map">Map</option>
<option value="Integer">Integer</option>
</select>
<select name="method" aria-label="Метод генерации">
<option value="Static">Static</option>
<option value="Random">Random</option>
<option value="Range">Range</option>
</select>
<input name="size" type="text" placeholder="Size">
<input name="value" type="text" placeholder="Value">
`;
function createChildElement(e) {
if(e.value == "List") {
var x = document.createElement('ul');
var z = document.createElement('li');
z.insertAdjacentHTML( 'beforeend', template );
x.appendChild(z);
e.parentNode.appendChild(x);
}
if(e.value == "Map") {
var x = document.createElement('ul');
var z = document.createElement('li');
z.insertAdjacentHTML( 'beforeend', template );
x.appendChild(z);
var y = document.createElement('ul');
var n = document.createElement('li');
n.insertAdjacentHTML( 'beforeend', template );
y.appendChild(n);
e.parentNode.appendChild(x);
e.parentNode.appendChild(y);
}
}
<body>
<div id="main-container">
<ul><li><div class="singleton-card ml-2">
<select name="type" onChange="createChildElement(this)" aria-label="Select type">
<option value="List">Select type</option>
<option value="List">List</option>
<option value="Map">Map</option>
<option value="Integer">Integer</option>
</select>
<select name="method" aria-label="Метод генерации">
<option value="Static">Static</option>
<option value="Random">Random</option>
<option value="Range">Range</option>
</select>
<input name="size" type="text" placeholder="Size">
<input name="value" type="text" placeholder="Value">
</div></li></ul>
</div>
</body>
I just found this example (https://codesandbox.io/s/github/vuejs/vuejs.org/tree/master/src/v2/examples/vue-20-tree-view?from-embed), I want to build something similar, but as a form with selects and inputs (just like my snippet example).
If I understand correctly, you're trying to create dependent dropdowns. You can check the following codepen for creating a dependent dropdown in vue.js
https://codepen.io/adnanshussain/pen/KqVxXL
JS
var model_options = {
1: [{ text: "Accord", id: 1 }, { text: "Civic", id: 2 }],
2: [{ text: "Corolla", id: 3 }, { text: "Hi Ace", id: 4 }],
3: [{ text: "Altima", id: 5 }, { text: "Zuke", id: 6 }],
4: [{ text: "Alto", id: 7 }, { text: "Swift", id: 8 }]
};
var makes_options = [
{ text: "Honda", id: 1 },
{ text: "Toyota", id: 2 },
{ text: "Nissan", id: 3 },
{ text: "Suzuki", id: 4 }
];
var vm_makes = new Vue({
el: "#app",
data: {
make: null,
model: null,
makes_options: makes_options,
model_options: model_options,
},
watch: {
make: function(event) {
$('#vehicle-models').dropdown('clear');
}
}
});
$('.ui.dropdown').dropdown();
HTML
<div id="app" class="ui grid">
<div class="row">
<div class="column">
<div class="ui label">Vechicle Make</div>
<select class="ui dropdown" v-model="make" id="vehicle-makes">
<option v-for="option in makes_options" v-bind:value="option.id">
{{ option.text }}
</option>
</select>
</div>
</div>
<div class="row">
<div class="column">
<div class="ui label">Vechicle Model</div>
<select class="ui dropdown" id="vehicle-models" v-model="model">
<option
v-for="option in model_options[make]"
:value="option.id"
:key="option.id"
>
{{ option.text }}
</option>
</select>
</div>
</div>
</div>

Angular 2 changing disabled/enabled select options

I'm using Angular2 and I have 2 selects:
<div ng-controller="ExampleController">
<form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect">
<option *ngFor="let company of companies"
value="{{company.id}}"> {{company.name}}
</option>
</select>
<label for="documentTypeSelect"> Type: </label>
<select name="documentTypeSelect" id="documentTypeSelect">
<option value="type1">type1</option>
<option value="type2">type2</option>
<option value="type3">type3</option>
</select>
</form>
<hr>
</div>
I want to change second select options depending on the first select. I can get types (boolean value) by using
company.companyRelations.pop().type1
company.companyRelations.pop().type2
And now, if for example type1 is false, the option in second select should be disabled and if type2 is true, option should be enabled. Is that possible?
EDIT:
Companies in select have deasdv, invoic and orders properties which are true or false. How can i now pass these properties into component.ts properties? Is it possible by event or what? I want to get for example
company.companyRelations.pop().desadv
For company which is selected and it will change disabled options in the second one.
html
<form name="myForm">
<label for="companySelect"> Company: </label>
<select class="form-control" name="companySelect" id="companySelect"
[(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company.id">
{{company.name}}</option>
</select>
<select name="documentTypeSelect" id="documentTypeSelect">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option [disabled]="!desadv" value="desadv">desadv</option>
<option [disabled]="!invoic" value="invoic">invoic</option>
<option [disabled]="!orders" value="orders">orders</option>
</select>
</form>
component.ts
desadv: boolean = false;
invoic: boolean = false;
orders: boolean = false;
and here it will be something like:
onChange(event) {
if(event.desadv) {
this.desadv = true;
}
}
My solution:
html
<form name="myForm">
<label for="companySelect"> Company: </label>
<select name="companySelect" id="companySelect" [(ngModel)]="companySelect"
(ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company">
{{company.name}}</option>
</select>
<label for="documentTypeSelect"> Type: </label>
<select name="documentTypeSelect" id="documentTypeSelect">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option [disabled]="!desadv" value="desadv">desadv</option>
<option [disabled]="!invoic" value="invoic">invoic</option>
<option [disabled]="!orders" value="orders">orders</option>
<option [disabled]="!recadv" value="orders">recadv</option>
<option [disabled]="!shipment" value="orders">shipment</option>
</select>
component.ts
onChange(event) {
this.desadv = event.companyRelations[0].desadv;
this.invoic = event.companyRelations[0].invoic;
this.orders = event.companyRelations[0].orders;
this.recadv = event.companyRelations[0].recadv;
this.shipment = event.companyRelations[0].shipment;
}
Try this :
<select class="form-control" name="companySelect" id="companySelect" [(ngModel)]="companySelect" (ngModelChange)="onChange($event)">
<option [ngValue]="undefined" disabled selected>Select...</option>
<option *ngFor="let company of companies" [ngValue]="company.id">{{company.name}}</option>
</select>
<select [disabled]="btnDisable" name="documentTypeSelect" id="documentTypeSelect">
<option value="type1">type1</option>
<option value="type2">type2</option>
<option value="type3">type3</option>
</select>
component.ts
private companySelect: any;
private btnDisable: boolean = true;
onChange(event) {
if(event) {
this.btnDisable = false;
}
}
Yes it is possible.
I have created a demo in which second drop down will be enabled depending upon the value of flag in first drop down object.
// Code goes here
var myApp = angular.module('plunker',[]);
angular.module('plunker').controller('MyCtrl', MyCtrl)
MyCtrl.$inject = ['$scope'];
function MyCtrl($scope) {
$scope.items1 = [{
id: 1,
label: 'aLabel',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
'flag':false,
subItem: { name: 'bSubItem' }
}];
$scope.items2 = [{
id: 1,
label: 'MyName',
'flag':true,
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'YourName',
'flag':false,
subItem: { name: 'bSubItem' }
}];
$scope.changeDetect = function(){
$scope.selected1='';
console.log($scope.selected);
if($scope.selected.flag)
{
$scope.flagValue=false;
} else {
$scope.flagValue=true;
}
}
$scope.flagValue=true;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<div ng-app="plunker" ng-controller="MyCtrl">
<select ng-options="item as item.label for item in items1 track by item.id" ng-model="selected" ng-change="changeDetect()"></select>
<select ng-options="item as item.label for item in items2 track by item.id" ng-model="selected1" ng-disabled="flagValue"></select>
</div>
In AngularJS 2
<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
<option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
<select [ngModel]="selectedDeviceObj1" name="sel2" [disabled]="flag">
<option [ngValue]="i" *ngFor="let i of deviceObjects1">{{i.name}}</option>
</select>
onChangeObj(newObj) {
this.selectedDeviceObj1='';
console.log(newObj);
this.selectedDeviceObj = newObj;
if(newObj.flag){
this.flag = false;
}
else {
this.flag = true;
}
Please find Demo Link Plunkr

Angular JS- 1st Dropdown linked to 2nd linked to 3rd. Now I need selected data from 3rd drop down to display in another textarea

I have posted the script and the controller. From one drop down I goto the second one and from the second to third. for example amazon's website where you got categories then to electronics and then to mobile.
Now I want to take that selected mobile and put it in another textarea.
I am building a sales management project and I am new to angular JS.
<!--This is the script--!> <script>
function CategoryCntrl($scope) {
$scope.categories = {'Electronics': {
'Mobile': ['Samsung S6', 'Nokia 6', 'Motorola M2', 'Oneplus 3T'],
'EarPhones': ['House of Marley H76', 'Sennheiser S789', 'Creative T242'],
'Mouse': ['HP HP56', 'LG L11', 'Frontech F223']
},
'Clothing': {
'T-Shirt': ['Levis T-Shirt 1231', 'PEPE T P6534', 'UCB T D7678'],
'Shirt': ['Peter Englang P5466', 'Soldado S0944'],
'Trouser': ['Vero Moda V6767', 'Arrow A6799']
},
'Books': {
'Fiction': ['Red Serpant- Knox Vermount', 'Clove- Heather Tove', 'MajinBoo- Goku Gohan'],
'Non-Fiction': ['Wings of Fire - APJ']
}
};
}
</script>
----------------------------------------------------------------------- <!--This is the controller--!>
<div ng-controller="CategoryCntrl">
Category:
<select class="select form-control" id="category" ng-model="productTypes" ng-options="category for (category, productTypes) in categories">
<option value=''>Select</option>
</select>
Product Type: <select class="select form-control" id="productT" ng-disabled="!productTypes" ng-model="products" ng-options="productT for (productT,product) in productTypes"><option value=''>Select</option></select>
Product: <select class="select form-control" id="product" ng-disabled="!products || !productTypes" ng-model="product"><option value=''>Select</option> <option ng-repeat="product in products" value='{{product}}'>{{product}}</option></select>
</div>
----------------------------------------------------------------------------
<p>To be displayed here</p>
i have changed some areas in your code and seems to be working now.
Angular Controller Code
var app=angular.module('categoryApp',[]);
app.controller('categoryCntrl',['$scope',function($scope){
$scope.categories = {'Electronics': {
'Mobile': ['Samsung S6', 'Nokia 6', 'Motorola M2', 'Oneplus 3T'],
'EarPhones': ['House of Marley H76', 'Sennheiser S789', 'Creative T242'],
'Mouse': ['HP HP56', 'LG L11', 'Frontech F223']
},
'Clothing': {
'T-Shirt': ['Levis T-Shirt 1231', 'PEPE T P6534', 'UCB T D7678'],
'Shirt': ['Peter Englang P5466', 'Soldado S0944'],
'Trouser': ['Vero Moda V6767', 'Arrow A6799']
},
'Books': {
'Fiction': ['Red Serpant- Knox Vermount', 'Clove- Heather Tove', 'MajinBoo- Goku Gohan'],
'Non-Fiction': ['Wings of Fire - APJ']
}
};
}]);
Code for HTML template
<div ng-app="categoryApp">
<div ng-controller="categoryCntrl">
Category:
<select class="select form-control" id="category" ng-model="productTypes" ng-options="category for (category, productTypes) in categories">
<option value=''>Select</option>
</select>
Product Type: <select class="select form-control" id="productT" ng-disabled="!productTypes" ng-model="products" ng-options="productT for (productT,product) in productTypes"><option value=''>Select</option></select>
Product: <select class="select form-control" id="product" ng-disabled="!products || !productTypes" ng-model="product"><option value=''>Select</option> <option ng-repeat="product in products" value='{{product}}'>{{product}}</option></select>
</div>
</div>

In AngularJS, how to change the default option of a select?

I am using AngularJS. There are two select, the first is the "team select," the second is the "member select." If the "team select" have the members, the "member select" show " select the member ." If the "team select" don't have the members, the 'member select" show "no member."
My problem is how to change the default option of the "member select".
This is my code:
<script src="angular.js"></script>
<div class="bigDiv">
<select class="common_select" name="xxx" ng-options="item as item.teamname for item in team_array" ng-model="select_team" id="" ng-change="selectMemberFun(select_team)">
<option value="" disabled selected hidden>select a team</option>
</select>
<select class="common_select" name="xxxxx" id="" ng-options="item as item.name for item in select_team.members" ng-model="select_member">
<option ng-show="!have_member" value="" disabled selected hidden>no member</option>
<option ng-show="have_member" value="" disabled selected hidden>select a member</option>\
</select>
</div>
<script src="angular.js"></script>
<script>
angular.module('app',[]).controller('xxx',['$scope', function ($scope) {
$scope.have_member = false;
$scope.team_array = [
{teamname: "team1", members:[ {name:'team1member1'}, {name:'team1member2'}]},
{teamname: "team2", members:[ {name:'team2member1'}, {name:'team2member2'}]},
{teamname: "team3", members:[]},
];
$scope.selectMemberFun = function (team) {
if(team.members.length == 0){
$scope.have_member = false;
} else {
$scope.have_member = true;
}
}
}])
</script>
Why does the 'ng-show' directive not work ? The "member select" always shows "no member".
I've tried a few ways, looks like this one works.
angular.module('app', []).controller('TestController', ['$scope',
function($scope) {
$scope.have_member = false;
$scope.team_array = [{
teamname: "team1",
members: [{ name: 'team1member1' }, { name: 'team1member2' }]
}, {
teamname: "team2",
members: [{ name: 'team2member1' }, { name: 'team2member2' }]
}, {
teamname: "team3",
members: []
}, ];
$scope.selectMemberFun = function(team) {
if (team.members.length == 0) {
$scope.have_member = false;
} else {
$scope.have_member = true;
}
}
}
])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div class="bigDiv" ng-app="app" ng-controller="TestController">
<select class="common_select" name="xxx" ng-options="item as item.teamname for item in team_array" ng-model="select_team" id="" ng-change="selectMemberFun(select_team)">
<option value="" disabled selected hidden>select a team</option>
</select>
<select class="common_select" name="xxxxx" id="" ng-options="item as item.name for item in select_team.members" ng-model="select_member">
<option value="" disabled selected hidden>{{have_member ? 'select a member' : 'no member'}}</option>
</select>
</div>
According to the documentation -> https://docs.angularjs.org/api/ng/directive/select
<select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
<option value="">---Please select---</option> <!-- not selected / blank option -->
<option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
<option value="option-2">Option 2</option>
</select>
It doesn't work because ngOptions is like ngReapeat in that it will ONLY iterate when there are values in the select_team.members array. In Team3 the member array is empty, so all the inner <option></option> are skipped.

How to populate value in a select dropdown as default using angular js

<select data-ng-model="userInf.role" class="span12" required>
<option value="" selected="selected" disabled="disabled">Choose one</option>
<option data-ng-repeat="role in roles" value="{{ role.text }}">{{ role.text }}</option>
</select>
angular
userService.getUser($scope.userInf,
function( data ) // success
{
$scope.userInf = {
username: data.userName,
firstname: data.firstName,
middlename: data.middleName,
lastname: data.lastName,
title: data.title,
organization: data.organization,
role: data.authorization.role,
dateOfBirth:data.dateOfBirth,
save: 'update'
};
},
Other fileds are coming but select value is not coming
In inspect element i can see
<select data-ng-model="userInf.role" class="span12 ng-pristine ng-valid ng-valid-required" required="">
<option value="? string:Analyst ?"></option>
<option value="" selected="selected" disabled="disabled">Choose one</option>
<!-- ngRepeat: role in roles --><option data-ng-repeat="role in roles" value="Analyst" class="ng-scope ng-binding">Analyst</option>
<option data-ng-repeat="role in roles" value="Admin" class="ng-scope ng-binding">Admin</option>
</select>
I know that Angular has the ng-init directive for this very purpose. Why don'y you try the ng-options directive? You can use the ng-init directive side by side with ng-options, and ng-options is a little more flexible than ng-repeat.
<select ng-model="userInf.role" ng-options="role for role in roles" ng-init="userInf.role = '' " class="span12 ng-pristine ng-valid ng-valid-required" required="">
<option value="" disabled="disabled">Choose one</option>
</select>
The ng-init will set your ng-model, which is the value of the options defined below, to whatever you want, in this case, setting your ng-model to '' which is the value of your first option. The ng-options will populate the rest of your options for you with the values in your array. You might need some setup to display the correct names and values in your options. Look here https://docs.angularjs.org/api/ng/directive/select
Yeah, I would do it like this:
var app = angular.module('app', [])
app.controller('exampleCtrl', function ($scope) {
$scope.options = ["a", "b", "c"]
$scope.selected = $scope.options[1]
})
<select ng-options="o for o in options" ng-model="selected"></select>
Option "b" will be selected on load
<select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>

Categories

Resources