Disable selectbox with ng-options in angularjs - javascript

Hello how can I disable a select box, so that a user can only see the actual value of the select box and can't change the content inside. It's for an ionic framework mobile application.
My select box is looking like this one here:
<select ng-class="nightMode"
ng-options="option as option.label for option in item.Options track by option.id"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>
I tried with ng-disabled, disable inside the ng-options, ng-readonly but none of these worked for me. So what is the correct way to achieve this?
ng-disable example:
<select ng-class="nightMode"
ng-options="option as option.label for option in item.Options track by option.id"
ng-disabled="true"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>
Update:
I tried one of the workarounds like suggested:
<select ng-class="nightMode"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
<option ng-repeat="option in item.Options" value="option.id" ng-disabled="true" ng-selected="item.Checked.id==option.id">{{option.label}}</option>
</select>
But I can switch to a empty entry inside the select box and set the value of the selectbox to undefined.

Your code snippet not clear yet. But i can disable this select using disabled="true" .
Check out my working
http://plnkr.co/edit/xDefIzZ3YleYcyAmQYHj?p=preview
Here are better code snippet editor :
http://plnkr.co/
http://jsfiddle.net/

I guess your logic is wrong,
If you don't want to change content in selectbox, then it's not going to be a select element, just use an input and assign a model to it, then something changed, change the value of it.
<input type="text" name="selectedId" ng-model="selectedId" />
Other Implementation:
If you want to open select and don't able to select them,
then add your dynamic data to
var datas = [
{
"value" : "foo",
"id" : "0111",
"selectable": false
},
{
"value" : "foo",
"id" : "0111",
"selectable": true
}
];
Then use it on option element;
<option ng-repeat="option in item.Options" value="option.id" ng-disabled="true" ng-disabled="item.selectable">{{option.label}}</option>

Well it turned out that this was a ionic-framework item-select problem.
I found this issue to solve my problem:
https://github.com/driftyco/ionic/issues/1549
Like suggested there I end up adding a class to my select box which looks like this:
.style-disabled {
pointer-events: none;
}
And my select box is now looking like this:
<select class="style-disabled"
ng-class="nightMode"
ng-disabled="someCondition"
ng-options="option as option.label for option in item.Options track by option.id"
ng-change="item.Call(item.SettingKey,item.Checked.id)"
ng-model="item.Checked">
</select>

You can't do it the way you want, but there are some work around in previously asked question, check them 1 , 2
<div ng-app="myapp">
<form ng-controller="ctrl">
<select id="t1" ng-model="curval">
<option ng-repeat="i in options" value="{{i}}" ng-disabled="disabled[i]">{{i}}</option>
</select>
<button ng-click="disabled[curval]=true">disable</button>
</form>
angular.module('myapp',[]).controller("ctrl", function($scope){
$scope.options=['test1','test2','test3','test4','test5'];
$scope.disabled={};
})
I hope that helps, good luck

Related

Angular - my ngIf hides an input-label only once

*ngIf="currentIdea.oetSupportNeeded" I have a dropdown list with 2 values - yes and no, and another input label where you can write freely. I want to show the input-label only when user chose "yes" in the dropdown list and to hide it when "no" is chosen.
My problem is that the following code works only once - when page loads and "no" is chosen, the input label is hidden, but when you choose "yes" and then "no" again, the label shows up and doesn't disappear anymore. I want it to toggle on/off depending on the user's choice
I tried using ngShow, ngHide, [disabled], etc. Nothing helped
<div class="select-wrapper" [ngClass]="{'select-wrapper-blocked': isNotAdmin()}">
<select class="input-control" [(ngModel)]="booleanVariable">
<option value="false">No</option>
<option value="true">Yes</option>
</select>
</div>
</div>
<div class="col form-input" [ngClass]="{'form-input-blocked': isNotAdmin()}">
<p class="input-label">
Some text
</p>
<input *ngIf="booleanVariable" class="input-control" [(ngModel)]="stringVariable" />
</div>
According to the code you shared, the value of your select menu is bound to the booleanVariable property of your component.
Your *ngIf queries another property, so the condition is wrong. You should be checking the booleanVariable in the condition.
Something similar happened to me few hours ago. The problem was that
<option value="false">No</option>
<option value="true">Yes</option>
was wrong. I solved it with
<option [value]="false">No</option>
<option [value]="true">Yes</option>
That's because otherwise Angular does not "analyze" the value of the option but recognizes it as a string.
Use ngModelChange event and make a function to typecast the data.
Check the link for example. Show Hide Field using *ngIf
You are using true and false as strings. You can change the test into your ngIf.
Like
<select [(ngModel)]="foo">
<option [ngValue]="true">true</option>
<option [ngValue]="false">false</option>
</select>
<input *ngIf="foo == true"/>
And to define a default value, you can set the value of foo into the class like
public foo = true;

How to make a <div> show only when a certain <select> dropdown option is selected? The <select> options are populated with the ng-repeat directive

I have a select dropdown list populated with the angularjs ng-repeat directive. I would like for a div to show only when a certain option is selected.
Here is the code:
<select type="text"
class="form-control"
ng-model="vm.request.requestType"
name="requestType" id="requestType"
placeholder=""
required>
<option selected></option>
<option value="test">test</option>
<option ng-repeat="requestType in vm.requestTypes">{{requestType}}</option>
</select>
<script>
$(function() {
$("#requestType").change(function () {
if ($("#test").is(":selected")) {
$("#continueCheckbox").show();
} else {
$("#continueCheckbox").hide();
}
}).trigger('change');
});
</script>
<div id="continueCheckbox">
<input type="checkbox"
name="continueCheckbox"
value="continueCheckbox">
Check this box to continue, and to confirm that you have read the
Documentation
</div>
The "test" option is just for testing if the function works. Currently, the checkbox displays no matter what is selected, and never disappears.
I highly recommend not mixing AngularJS and jQuery. Both are DOM manipulation frameworks and do not work well together. Here is one way you could accomplish what you are after with AngularJS:
<div id="continueCheckbox" ng-if="vm.request.requestType === 'test'">
<input type="checkbox"
name="continueCheckbox"
value="continueCheckbox">
Check this box to continue, and to confirm that you have read the Documentation
</div>
Have you tried using the ng-class directive?
<div id="continueCheckbox" ng-class="selected: vim.request.requestType === 'test'"></div>
Then handle the style in .css file
.selected {
display: none;
}
If you wanted to use jQuery, you could just check the value of the select. You have it set up already.
var selectType=$(this).val();
if (selectType=="test") // instead of if ($("#test").is(":selected"))
You could also use vanilla JS with .value to do your comparison.

How can I set default value for option angular

I have select like this
<select ng-model="form.data">
<option value="c" ng-repeat="c in data">{{c}}</option>
</select>
$scope.data= response.data
When I change select and click save . It save successful in database . I want when refresh page . select show value I save in database. How can I do this . Please help me
The best way would be using the ng-options directive:
<select ng-model="form.data" ng-options="c for c in data"></select>
This way, when refreshing your page the select will be default set to the value of $scope.form.data, as expected.
Some advice :
Use ng-options directive instead of traditional option element.
To display the previous selected value on page refresh use HTML5 localStorage or sessionStorage.
Working Demo
Use ng-selected
<select ng-model="form.data">
<option value="c" ng-repeat="c in data" ng-selected="c == form.data">{{c}}</option>
</select>
For people who are searching for a answer in Angular | angular 2 | angular 4
try using NgValue and make sure your default options value is the model so NgValue="ModelName"
<select ng-model="form.data">
<option NgValue="form.data">yourdefaultoption</option>
<option NgValue="c" ng-repeat="c in data">{{c}}</option>
</select>

Smaller Work around for ng-pattern on Select

I am working on an angular app and I needed to put a pattern validation on a select element. Just using ng-pattern on select didn't work. So I created a hidden input with same model with ng-pattern on the hidden input, that didn't work either. So I created a text input with the ng-pattern and hid it via css. Which works beautifully.
Is there a smaller work around for this?
EDIT1: I think I should have added that the options are generated by ng-options
EDIT2: Edited the code snippet accordingly to show what I actually want.
function formCtrl($scope) {
$scope.options = ['Please Select','Value 1','Value 2'];
$scope.price = 'Please Select';
$scope.onSubmit = function (form) {
console.log(form.$valid);
}
}
.show-none {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit(myForm)">
<select ng-model="price" ng-options="o as o for o in options"></select>
<input type="text" class="show-none" ng-pattern="/^(?!.*(Please Select))/" ng-model="price" name="price_field"> <span ng-show="myForm.price_field.$error.pattern">Not a valid option!</span>
<input type="submit" value="submit" />
</form>
</div>
You shouldn't use ng-pattern with hidden input field for this case, you should add value for each option, & then you should have required attribute make sure any of the option should selected before submiting. Adding name="price" will add form element to myForm object.
Markup
<select ng-model="price" name="price" required>
<option>Please Select</option>
<option value="TEST1">TEST1</option>
<option value="TEST2">TEST2</option>
</select>
Update
If you wanted to make it using ng-options then it would be something like below. You don't need to add Please Select in your array, you could add it manually inside select
Markup
<form name="myForm" ng-submit="onSubmit(myForm)" novalidate>
<select ng-model="price" ng-options="o for o in options" required>
<option value="">Please select a person</option>
</select>
<input type="submit" value="submit" />
</form>
Code
(function(angular) {
'use strict';
angular.module('staticSelect', [])
.controller('formCtrl', ['$scope', function formCtrl($scope) {
$scope.options = ['Value 1', 'Value 2'];
$scope.onSubmit = function(form) {
console.log(form.$valid);
}
}]);
})(window.angular);
Demo here
You can also just disable certain options if you didn't want it to be possible to select them in the first place:
<select ng-model="price">
<option disabled>Please Select</option>
<option>TEST1</option>
<option>TEST2</option>
</select>
Chiming in here as this is something that comes up time and time again and the suggested solutions here don't work for me. This is a really common use-case too.
I tried putting an empty option in, and it didn't work for me. I noticed that AngularJS was placing a value attribute in with the same value as the contents of the <option> tag. The select was ng-valid even with this option selected.
In my scenario I have placed the placeholder option i.e. SELECT A CENTRE as the first item in the list of locations (the scope variable I bind the options to). I hide the first item with conditional CSS, but select it initially by setting dc.user.CentreName to SELECT A CENTRE in the controller. This gives us the behaviour of it disappearing when the user has clicked any other option. Another option is to disable it which means it will still show at the top of the list but will be unselectable after selecting another item (was added in Angular 1.4x). I have also put that code in (the ng-disabled attribute), to illustrate this. You may safely remove it if you want to go the hidden route.
Next we want to use the standard Angular forms validation to ensure that some item other than the first is selected. I tried the other suggested approaches of putting in an empty option (with no value) and setting required on the select. So I went for a hidden input form element with a required and ng-pattern attribute using a negative lookahead assertion.
Note that we use ng-class to bind ng-valid and ng-invalid to the select so existing CSS styling will work.
Feels a bit hacky but it works.
<select ng-model="dc.user.CentreName"
ng-class="{'ng-valid': orderForm.centreName.$valid, 'ng-invalid': !orderForm.centreName.$valid }">
<option ng-repeat="location in locations"
ng-disabled="$index < 1"
ng-style="$index < 1 && {'display': 'none'} "
value="{{location}}">
{{location}}
</option>
</select>
<input
type="hidden"
ng-model="dc.user.CentreName"
ng-pattern="/^(?!SELECT)/"
required/>
And in the controller... (note you can also use ng-init to set the placeholder value declaratively from the view, see https://stackoverflow.com/a/13775151/4707368)
function ShoppingController($scope [...]) {
[...]
$scope.dc = {
user: {
"CentreName": 'SELECT A CENTRE',
[...]
Your CSS might look like this:
input.ng-touched.ng-invalid, select.ng-invalid
{
background-color: rgba(199, 35, 35, 0.15);
}
input.ng-touched.ng-valid, select.ng-valid
{
background-color: rgba(116, 173, 39, 0.16);
}

Startup value does not set selected value

I've made a simple angular.js example which shows my problem: example
I want to set the start value of the select element to a specific value.
<select name="i" id="i" ng-model="selectedItem">
<option ng-repeat="i in items" value="{{i}}">{{i}}</option>
</select>
The options and the select element get rendered perfectly. But, like in the example, when i set the value in my controller to 6, the selected value on the page is still the first element.
scope.selectedItem = 6;
There are 2 simple buttons which just change the selected value. When you press them the selection change without problems.
EDIT: i updated the jsfiddle and removed unused code and renamed code to make things a bit more clear
EDIT2: I missed to ask if it is possible to fix the second select element too? The different is that this array contains objects instead of numbers.
<select name="o" id="o" ng-model="selectedItem">
<option ng-repeat="o in objects" ng-value="{{o.ID}}">{{o.Text}}</option>
</select>
You should not use ngRepeat to render option elements, it's not supposed to work properly with select and options. Use ngOptions which will work as expected with ngModel:
<select name="i" id="i"
ng-model="selectedItem"
ng-options="i for i in items">
</select>
For the second selectbox which has ngModel bound to ID property of the objects in array, it will be:
<select name="o" id="o"
ng-model="selectedItem"
ng-options="obj.ID as obj.Text for obj in objects">
</select>
Demo: http://jsfiddle.net/d3jf7ueq/9/

Categories

Resources