I have an data in below given format
{
USA: {
CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
LA: { 'BATON ROUGE':['70898','70895','70891'] }
}
}
trying to add them to dependent drop downs namely Country, State, City and Zip code. I'm using ng-option but while getting the value for country dropdown its returning oject:16 instead of value.
$scope.countries = {
USA: {
CA: { 'SAN FRANCISCO':['94188', '94158', '94143'] },
LA: { 'BATON ROUGE':['70898','70895','70891'] }
}
}
$scope.GetSelectedCountry = function () {
$scope.strCountry = document.getElementById("country").value;
}
<b>Country:</b>
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
<option value=''>Select Country</option>
It is not the Angular way to get values.
You use <select ng-model="statessource" ...>, so the value of the select is stored in $scope.statessource.
This should works:
$scope.GetSelectedCountry = function() {
$scope.strCountry = $scope.statessource;
}
You have used an ng-model variable for your select tag, but you have not used that in your controller to get the selected value. There is no need to access the value using javascript dom selector, instead you can directly use the model value of the select tag $scope.statessource.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
$scope.countries = {
USA: {
CA: {
'SAN FRANCISCO': ['94188', '94158', '94143']
},
LA: {
'BATON ROUGE': ['70898', '70895', '70891']
}
}
}
$scope.GetSelectedCountry = function () {
$scope.strCountry = $scope.statessource;
console.log($scope.strCountry);
}
});
</script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<b>Country:</b>
<select id="country" ng-model="statessource" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry()">
<option value=''>Select Country</option>
</select>
</body>
</html>
If your only concern is to get the currently selected value each and every time a user changes it, your ng-model will already handle this case.
So, by using this
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries">
Angular would always apply its two-way-data-binding to store the currently selected option inside your $scope.statessource-variable.
Other than that, if you want to do other stuff related to a change of the selection, you can do the following:
<select id="country" ng-model="statessource" ng-disabled="!type" ng-options="country for (country, states) in countries" ng-change="GetSelectedCountry(statessource)">
$scope.GetSelectedCountry = function (newState) {
// Do something with your newState variable.
// Remember, $scope.statessource still includes the currently selected
// option
}
I hope that helped :)
The way to access the selected value of an OPTION nested in a SELECT is here:
var e = document.getElementById("country");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;
Related
When I reload the page, the first option is always empty. I want the option containing text Any Make to be the default select option. Here is the code for my view:
<select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0" selected="selected"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
here is my controller code:
.controller("homeController", function ($scope, makeData, $http) {
$scope.makeData = makeData;
$scope.makeChanged = function () {
$http({
method: "GET",
url: "homeService.asmx/GetModelById"})
.then(function (response) {
$scope.modelData = response.data;
})
}
})
just remove ng-init and in your model give default value
$scope.makeSelected = 0;
Here is a running fiddle for your code Click here
Fiddle for code with dynamic data Click here
If you aren't going to use ngOptions, at least get rid of that ng-init since it isn't a function, and in the controller function set $scope.makeSelected = 0;
Then you can remove the selected="selected" on that initial option, since the angularJS code will be handling what is selected.
See a demonstration below:
angular.module('app', [])
.value('makeData', [{
"make_id": 1,
"make_name": "cat"
},{
"make_id": 2,
"make_name": "dog"
},{
"make_id": 6,
"make_name": "monkey"
}])
.controller("homeController", function($scope, makeData, $http) {
//initialize the value associated with ng-model on the select list
$scope.makeSelected = 0;
$scope.makeData = makeData;
$scope.makeChanged = function() {
console.log('makeChanged');
//$http() request removed because we don't have access outside this domain for AJAX requests.
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
<select class="form-control" id="make" name="make" ng-model="makeSelected" ng-change="makeChanged()">
<option value="0"> Any Make</option>
<option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
</select>
<div>makeSelected: {{makeSelected}}</div>
</div>
I need to change the 'selected' attribute of a html option element within a select object using javascript.
I already tried this: Solution
This is what I have:
.cshtml
<div class="form-group form-group-default" id="divStateEUA">
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA" data-init-plugin="select2" style="width: 100%">
#foreach (var state in ViewBag.EUAStates)
{
<option>#state</option>
}
</select>
</div>
javascript
<script>
$(document)
.ready(function () {
CheckState();
});
function CheckState() {
if (selectedText == 'Estados Unidos') {
var element = document.getElementById('listStateEUA');
element.value = 'Chicago';
}
}
</script>
rendered html:
And still not working. Any ideas?
You are missing value attribute in the option tag of select.
Modify your razor code to have value attribute in option tag, so that you can change the combo-box selection on basis of value :
#foreach (var state in ViewBag.EUAStates)
{
<option value="#state">#state</option>
}
and now in your jquery code, you should be able to do :
function CheckState() {
if (selectedText == 'Estados Unidos') {
$("#listStateEUA").val("Chicago");
}
}
You must provide a value for the options. Your JS is trying to set the select to the "Chicago" value, but none exists. <option>Chicago</option> vs <option value="Chicago">Chicago</option>
function CheckState() {
var element = document.getElementById('listStateEUA');
element.value = 'chicago';
}
CheckState();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Estado</label>
<select id="listStateEUA" name="listStateEUA">
<option value="nevada">nevada</option>
<option value="chicago">chicago</option>
<option value="arizona">arizona</option>
</select>
As Mike McCaughan suggested (thank you very much), since I'm using select2 plugin, it have a different way to get and set values.
$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value
Answer found here: select2 plugin get and set values
I´m working in Angular and I have fields to fill like
I fill my select list as:
function cargarCatalogo() {
apiService.get("../../api/Catalogos/",
null,
function(res) {
//console.log(res.data);.
$scope.Catalogos = res.data;
$scope.selected = $scope.Catalogos[0];
},
errorCatalogo);
}
I want to know how can I pass selected Value into url in my funcion:
function actualizar(vehiculo) {
$scope.vehiculo.Origen = $scope.usuario.Origen;
$scope.vehiculo.Version = $scope.Version;
apiService.post("../../api/AddCatalogoRegistro/" + selected.ID,
function(res) {
// my code
How can I pass that selected value as a selected.ID, chrome console throw me
ReferenceError: selected is not defined
View:
<select class="form-control" ng-change="filtro(selected)" ng-init="Catalogos[0]" ng-model="selected" ng-options="item.Nombre for item in Catalogos">
<option></option>
</select>
Use $scope.selected as ng-model value
<select class="form-control" ng-change="filtro(selected)"
ng-init="Catalogos[0]" ng-model="selected"
ng-options="item.Nombre for item in Catalogos">
It should solve your problem. And the best practise is to name the controller and use ng-model = "ctrlName.selected"
My Dropdown is not set with its ng-model Value in Edit-Profile Case
Here is my Controller.js method which calls service.js method and get data from database in Json format
function CountryList() {
var getUserData = crudAJService.CountryList(); // calls Service method
getUserData.then(function (response) {
$scope.countryList = response.data;
}, function () {
console.log("Can't read Country data");
});
I get countryList properly and html is rendered as expected (as I expect)
<select class="form-control ng-pristine ng-valid ng-valid-required ng-touched" name="country" required="" ng-model="countryid"
ng-options="option.Value as option.Text for option in countryList" ng-change="GetSelectedState(countryid)">
<option value="" class="" selected="selected">Choose Country</option>
<option value="1" label="India">India</option>
<option value="2" label="USA">USA</option>
<option value="3" label="China">China</option>
<option value="4" label="UK">UK</option>
<option value="5" label="Australia">Australia</option>
<option value="6" label="koria">koria</option>
<option value="7" label="Pakistan">Pakistan</option>
</select>
There is also ng-change Method for getting state from Db with respect to countryId (Cascading-Dropdown) which is also fetched smoothly and rendered properly.
but in Edit Profile case my dropdown is not set on ng-model value.?(not set selected value)..
if I bind {{countryid}} than it is also get proper result in my form(for testing purpose).
Here is my EditUser() method which is called when Edit button pressed from gridView.
$scope.EditUser = function (user) {
var getUserData = crudAJService.getUser(user.UserID);
getUserData.then(function (_user) {
CountryList(); //this method is mention above.
$scope.user = _user.data;
$scope.firstName = user.FirstName;
$scope.lastName = user.LastName;
$scope.countryid = user.CountryID;
Blah.. Blah.. So on
}, function () {
alert('Error in getting User records');
});
I think I had given all the necessary information with code. but still if You want any info plz tell me.
UPDATE
As you Suggest I make an object for ng-model and than I changed HTML Like this
<select class="form-control" name="country" required="" ng-model="countryModel" ng-options="countryModel.Value as countryModel.Text for countryModel in countryList" ng-change="GetSelectedState(countryModel.Value)">
now my controller.js EditUser() method is Looks Like this Image ..
(See Image.)
ng-model should be an object with two properties Value and Text. While ng-option is an array of objects. So in your case your countryList is like this:
$scope.countryList = [{Value: 1, Text: "India"}, {Value: 2, Text: "USA"}]
So countryid must be an object like this:
$scope.countryid = {Value: 1, Text: "India"}
UPDATE
If you only have country value then you can use this to build 'countryId' object:
let selectedId = 1;
$scope.countryId = $scope.countryList.filter(function (country) {
return country.Value == selectedId;
})[0];
Your HTML for select element will then become like this:
<select class="form-control" name="country" required="" ng-model="countryModel" ng-options="countryOpt as countryOpt.Text for countryOpt in countryList" ng-change="GetSelectedState(countryModel.Value)">
Hey I'm trying to create a form with a dropdown menu containing states are automatically filtered based on selected country. That is, only show the states of the selected country
JQuery
$("#shipment_sender_attributes_state_code").parent().hide()
$('#shipment_sender_attributes_country_code').change(function() {
states = $("#shipment_sender_attributes_state_code").html()
country = $('#shipment_sender_attributes_country_code :selected').val()
options = $(states).filter("optgroup[label='" + country + "']").html()
$states = $('#shipment_sender_attributes_state_code')
if (options) {
$states.html(options)
$states.parent().show()
} else {
$states.empty()
$states.parent().hide()
}
})
It works the first time I select a country, but if I select another, and then go back, the states variable remains empty and no drop down is shown. Any advice?
Form:
<optgroup label="us">
<option value="AA">Armed Forces Americas (AA)</option>
<option value="AE">Armed Forces Europe (AE)</option>
<option value="AK">Alaska (AK)</option>
<option value="AL">Alabama (AL)</option>
<option value="AP">Armed Forces Pacific (AP)</option>
<option value="AR">Arkansas (AR)</option>
....
<optgroup label="ca"><option value="AB">Alberta (AB)</option>
<option value="BC">British Columbia (BC)</option>
<option value="MB">Manitoba (MB)</option>
<option value="NB">New Brunswick (NB)</option>
<option value="NL">Newfoundland and Labrador (NL)</option>
....
EDIT JSfiddle
Can't quite get the fiddle working, but it's something like this
http://jsfiddle.net/d6cm5v6g/2/
Use var to declare your variables.
var states...
var country...
var options...
If you don't do that you are creating global variables
You need to do a minor change to your code:
$(function(){
$("#shipment_sender_attributes_state_code").parent().hide()
var states = $("#shipment_sender_attributes_state_code").html()
$('#shipment_sender_attributes_country_code').change(function() {
var country = $('#shipment_sender_attributes_country_code :selected').val()
var options = $(states).filter("optgroup[label='" + country + "']").html()
var $states = $('#shipment_sender_attributes_state_code')
if (options) {
$states.html(options)
$states.parent().show()
}
else {
$states.empty()
$states.parent().hide()
}
})
});
You need to move states outside the change function because in your else you do this $states.empty(), so the next time there is no html to filter(all options and optgroups are gone). This way you store the original value in an object.
I change the Afganistan value to "ca" in order for testing purposes(you can switch between Afganistan and United States)
Working fiddle:http://jsfiddle.net/robertrozas/4vxjpjLv/2/