Pre select an "unknown" option in AngularJS - javascript

I'm trying to pre select an option in a select dropdown, I know how to do it if the value for the options are static. But what if they change dynamically? In my case I got a list of albums which updates a lot so I never know what the value of the options will be. I tried selecting the first album in the list by using ng-init like this:
<select class="rounded bold" ng-model="selectedAlbum" ng-init="selectedAlbum='album[0].albumName'">
<option ng-repeat="album in albumsList" value="{{album.albumName}}" ng-bind="album.albumName">
</select>
But with no luck, from my searches I can't really find anything that answers this. It might be ng-options but from what I've seen that doesn't generate options with a binding on them. Like I've done in the code above.
How would I achieve this?

Use the ng-options directive to build you list, and include an option with an empty value:
<select class="rounded bold"
ng-model="selectedAlbum"
ng-options="album.albumName for album in albumsList">
<option value="">-- choose album--</option>
</select>
See this jsBin

In your controller just change the selectedAlbum model to the value you want
$scope.selectedAlbum = albumsList[0].albumName

If albumsList changes, the model (selectedAlbum) may not match any albumName. In this case, selectedAlbum will remain on its previous value, and angular adds an "unknown" option to your select. As I understood your question,in this situation, you want the first item in the new albumList to be selected (which BTW I think is a reasonable action).
In order to achieve this, you can watch albumList and check if selectedAlbum is valid according to new albumList. If not, you can change it to first item:
$scope.$watch("alubmList", function(newAlbumList){
if(angular.isArray(newAlbumList) && newAlbumList.length){
var albumNames = newAlbumList.map(function(album){
return album.name;
});
if(albumNames.indexOf($scope.selectedAlbum)<0)
scope.selectedAlbum = newAlbumList[0].name;
}
});
side note:
you can rewrite your html with ng-options:
<select class="rounded bold" ng-options="album.albumName for album in albumsList"></select>

Simply u can make this with old JavaScript :
var elementid=document.getElementById("elementid");
var unknown_option=elementid.options[1].value;
elementid.value=unknown_option;
//options[1] selects the first option, if 2 then the 2nd.. etc
but of course if u want the last option u will have to make length function then loop or directly "inverted index" :)

Related

How to set initially selected option in select control with Angular

Please could I ask for help with the following:
I have a select control defined as below and I populate it's options with strings from an array of strings in my component called tools.Attributes.Serials It works fine:
<select class="noBorder additionalSelectStyle" name="filter_for" (change)="OnSerialChanged($event.target)">
<option *ngFor = 'let serial of tools.Attributes.Serials'>
{{serial}}
</option>
</select>
The displayed list will show the first item as the selected one.
Say I have a variable in my component's .ts code called nMyIndex = 1.
What code do I need to bind to nMyIndex so that the list appears with item 1 as default rather than item 0?
Thanks for any help,
OK, I found it, working now. Need to use as shown in following code snippet:
; let i = index' [selected]="i == nMyIndex"

Want to add none as value in select multiple

I am using chosen.jquery.js for select field
<select chosen multiple data-placeholder="Select Body Part(s)"
ng-options="option.Name as option.Name for option in BodyPartList" ng-model="Body_Part">
<option value="" disabled>Select Body Part(s)</option>
</select>
But It shows only data-placeholder value in case of no data in model.
I want to show "Select Body Part(s)" as a option in list.
And user must not select this. Reason is that, I want to add dynamic "Unknown" value in list of Body_Parts. But it not reflect in list.
Same work for select having single selection.
I'm not seeing any problems with your code, as such. Like, I'm trying it and getting the visual behaviour I think you're wanting? Am I missing something?
Html just yours with ng-app etc, javascript is:
var myApp = angular.module('myApp', ['localytics.directives']);
myApp.controller('MyController', function($scope) {
$scope.BodyPartList = [
{ Name: "Arm" },
{ Name: "Leg" }
];
$scope.Body_Part = [];
});
Not sure if data-placeholder is actually doing anything.
Fiddle: http://jsfiddle.net/7187f6d9/
That said, it's not "working". In the fiddle I put a regular select box alongside the chosen one, and the chosen one doesn't seem to be writing to the ng-model correctly. I'm not sure what's up with that.
You can choose the below option
https://harvesthq.github.io/chosen/#optgroup-support
or push another item to the top of the array from server side as your custom label and disable it on client side with the help of ng-if and $index properties of ng-repeat and angularjs. If this make sense then its fine else i can give you a demo.
I hope your query is, you want show a place holder as current selected value but user shouldn't be able to select it.
Instead of making it disabled, make ithidden. Then display an error if a user doesn't select any other options, using the value of placeholder option.
A sample snippet is added below. If value of select is Error, write a case to throw a error back to user.
<select>
<option value="Error" hidden>Select any Company</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
<option value="BMW">BMW</option>
</select>
Hope this helps! If not, ping me with your query. :)

How to get the selected value of some random dropdown in Javascript/jQuery

<select ng-model="myModel" id="searchAsset" class="search">
<option ng-repeat="asset in assettype" ng-click="assetclick()" value="{{asset}}"></option>
</select>
<select class="search" id="searchLevel">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
While performing some logic on second dropdown, I want to fetch the selected value of the first dropdown or vice-versa. How can I do this?
I tried using $("#searchLevel").value and $("#searchLevel option:selected").text()
The direct answer to this question is to use the .val() method for jQuery like so:
var selectedVal = $("#searchLevel").val();
However, the slightly less direct, but true answer is that you should not be doing anything like this in an angular app - changes in the dom should only be affecting your view model.
When your using angular, jquery is really not required.
As per your code, The first select menu value will be stored in the ng-model attribute value i.e. myModel.
In your second select menu, specific the ng-model as well. You can just fetch the value of the drop down menu by calling ng-model name.
<select class="search" id="searchLevel" ng-model="secondSelect">
<option class="chooseLevel" ng-repeat="level in levellist" value="{{level}}"></option>
</select>
For example,
If you want to access the value inside your controller on change event, then
$scope.changeEventhandlerForFirstSelect = function() {
// $scope.myModel will contain the value
}
Similarly, for second select menu $scope.secondSelect will give that value.
try
$("#searchLevel").val();
with: $("#searchLevel option:selected").text() you get the text not the value.

Angular blank option selected

I'm banging my head against the wall on this one.
I have an array of objects that will be used to populate a select drop down:
CardCount = [{"ClientId": "0010", "Description": "0010 (206 Members)"}, {"ClientId": "0051", "Description": "0051 (1 Member)"}, ........]
When I attempt to use ng-options, the value of the option is set to the index, not to the ClientId as desired. To get the value in each option to be the ClientId, I have to use a ng-repeat in the options. Here is my html:
<select ng-model="CurrentClient">
<option ng-repeat="item in CardCount" value="{{item.ClientId}}">{{item.Description}}</option>
</select>
Initially, all is well, the select and options are generated correctly, and the first option is correct. Now, when a certain button is clicked somewhere else on the page, it becomes necessary to recreate this select and options with a smaller array of similar objects. However, doing so creates a blank option with a value of "? string:0010 ?". This is the option that is selected. Again, I cannot use ng-options to correct this problem because doing so doesn't set the value attribute in the option tags correctly. So, I added this to the option tag:
<option ng-repeat="item in CardCount" value="{{item.ClientId}}" ng-selected="CurrentClient == item.ClientId">{{item.Description}}</option>
Now, that does mark the correct option as selected. However, the drop down still shows the blank option. Here's the rendered html:
<select ng-model="CurrentClient">
<option value="? string:0010 ?"></option>
<option value="0010" selected="selected">0010 (206 Members)</option>
</select>
As you can see, it sets the correct option to selected. However, it sets it to selected="selected", and not just selected. When I inspect element and change selected="selected" to selected (remove the equals and everything after it), the drop down then correctly displays the correctly selected option.
Again, initially the select and options work great. The problem seems to happen only after the array that the select is created with is changed. How can I get this select and options working correctly after I change the array, and not show that first blank option?
Thanks!
Changed you option element to set value by default.
<option ng-repeat="item in CardCount track by item.ClientId"
value="{{item.ClientId}}">{{item.Description}}</option>
Hope this could help you. Thanks.
ng-options is definitely the way to go:
<select ng-model="selected.ClientId" ng-options="it.ClientId as it.Description for it in clientList">
<option value="">-</option>
</select>

AngularJS selecting multiple options

So, What I'm trying to do is fairly simple with vanilla JS, but I'm using AngularJS and I would like to know how to do it the best way within the framework. I want to update the selected options in a multiple select box. I do not want to add or remove any of the options. Here is what my HTML looks like:
<select multiple>
<option value="1">Blue</option>
<option value="2">Green</option>
<option value="3">Yellow</option>
<option value="4">Red</option>
</select>
Using the following array, I'd like to programmatically select/deselect options from this list:
[{id:1, name:"Blue"},{id:4, name:"Red"}]
When I set this array in the scope, I want the select box to deselect anything that is not Blue or Red and select Blue and Red. The standard response that I've seen on the Google Groups is to use ng-repeat. However, I can't recreate the list every time because the list of selected values is incomplete. As far as I can tell, AngularJS has no mechanism for this, and I'm at a loss as to how I would do this without resorting to using jQuery.
ngModel is pretty awesome! If you specify the indexes as a model selectedValues
<select multiple ng-model="selectedValues">
built from your list (selected) in a $watch
$scope.$watch('selected', function(nowSelected){
// reset to nothing, could use `splice` to preserve non-angular references
$scope.selectedValues = [];
if( ! nowSelected ){
// sometimes selected is null or undefined
return;
}
// here's the magic
angular.forEach(nowSelected, function(val){
$scope.selectedValues.push( val.id.toString() );
});
});
ngModel will automatically select them for you.
Note that this data binding is one-way (selected to UI). If you're wanting to use the <select> UI to build your list, I'd suggest refactoring the data (or using another $watch but those can be expensive).
Yes, selectedValues needs to contain strings, not numbers. (At least it did for me :)
Full example at http://jsfiddle.net/JB3Un/

Categories

Resources