I am trying to show different data from a large data object based on selections made in view via a select box. I am populating the data like this
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
And I have ng-model on my select options.
<select ng-model="networkType">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
I initialize both of these variables
$scope.selectedType = 'individual';
$scope.networkType = 'inNetwork';
And the $scope.displayData is initially correct. However when I change the drop downs, the displayData does not change its values to access the new data. I am not sure what step I am missing here.
I think you should update the display data using ng-change event.
Add a update function in your controller
$scope.updateDisplay = function() {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
};
Add ng-change for your <select> element
<select ng-model="networkType" ng-change="updateDisplay()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="updateDisplay()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Or do it with $scope.$watch.
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed.
In my example, we are setting up a watch on both networkType and selectedType models. And instead of it being a funtion we simply put the $scope model name.
$scope.$watch('[networkType,selectedType]', function(newValues, oldValues) {
$scope.displayData = $scope.dataObj[newValues.selectedType][newValues.networkType];
});
Add this method to your controller
$scope.onChnage = function () {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
}
Html
<select ng-model="networkType" ng-change="onChnage ()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="onChnage ()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Beside $watch and ng-change, if you just want to display the data in displayData variable, another option is to convert it to a function display():
$scope.display = function () {
return $scope.dataObj[$scope.selectedType][$scope.networkType];
};
and in the view:
{{display()}}
this function will be called again whenever selectedType or networkType change
Related
I am using Jquery chosen plugin and it's working fine. I have used this plugin in my one of the module. My dropdown values are something like that:
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
It's working fine. But problem is that when user select first option and then try to change third option onchange event does not fire because both options values are same. Is there any way to call onchange event every time if values are same or differ ?
Options values is a unique key of item so it's repeated in dropdown. Dropdown value is duplicate we have allowed to use same item in others module
I saw your implementation and it is working fine in code pen here is the link no need to change anything
<select id="itemcode" onchange="get_data()">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
var get_data =function(){
alert("saas")
}
http://codepen.io/vkvicky-vasudev/pen/dXXVzN
Try this
$('#itemcode').click(function() {
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="itemcode">
<option value="1">ITEM001-A</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001-B</option>
<option value="3">ITEM003</option>
</select>
Edit: This doesn't work. Sorry!
You could add a data attribute that differs for each element, for example:
<select id="itemcode" onchange="get_data()">
<option value="1" data-id="1">ITEM001</option>
<option value="2" data-id="2">ITEM002</option>
<option value="1" data-id="3">ITEM001</option>
<option value="3" data-id="4">ITEM003</option>
</select>
If you're using Rails or another framework to generate the <option> tags, it should be easy to add an incremental id to each element.
There is no way to fire get_data() with your current data.
The solution below is more of a hack. When you populate the options, prepend the value with something unique.
Eg.
<select id="itemcode" onchange="get_data()">
<option value="1_1">ITEM001</option>
<option value="2_2">ITEM002</option>
<option value="3_1">ITEM001</option>
<option value="4_3">ITEM003</option>
</select>
Thus your get_data() method will be called everytime. And in your get_data() method, split the value using underscore _ and you can get the actual value there.
function get_data(){
var actualValue=$(this).val().split("_")[1];
//do other processing
...
}
You can use other characters like $, or anything you like, instead of _
Ideally you want to change the data coming from the backend so that you don't get duplicate data. However if this is not possible, another approach would be to sanitise the data before putting it in the select. E.g
https://jsfiddle.net/vuks2bpt/
var dataFromBackend = [
{key:1,
value: "ITEM0001"
},
{key:2,
value: "ITEM0002"
},
{key:1,
value: "ITEM0001"
},
{key:3,
value: "ITEM0003"
}
];
function removeDuplicates(array){
var o = {};
array.forEach(function(item){
o[item.key] = item.value;
});
return o;
}
function get_data(){
console.log('get_data');
}
var sanitised = removeDuplicates(dataFromBackend);
var select = document.createElement('select');
select.id = "itemcode";
select.addEventListener('change', get_data);
Object.keys(sanitised).forEach(function(key){
var option = document.createElement('option');
option.value = key;
option.textContent = sanitised[key];
select.appendChild(option);
})
document.getElementById('container').appendChild(select);
i am using jquery instead of java script
<select id="itemcode">
<option value="1">ITEM001</option>
<option value="2">ITEM002</option>
<option value="1">ITEM001</option>
<option value="3">ITEM003</option>
</select>
jquery
$('#itemcode:option').on("click",function(){
alert(saaas);
})
I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});
Learning more about AngularJS everyday.
A style contains style.StyleID,style.StyleName,style.EncryptedValue
I have the following code:
<select data-ng-model="StyleID"
data-ng-options="s.StyleID as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
I need to pass EncryptedValue into GetOptions() e.g (GetOptions(EncryptedValue)) or be able to access something like SelectedStyle.EncryptedValue
How do I go about doing that?
UPDATE
Changed my code to:
<select data-ng-model="style"
data-ng-options="s.StyleID as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
My Controller:
$scope.GetOptions = function ()
{
alert($scope.style);
}
alert($scope.style); returns a string of the StyleID
alert($scope.style.StyleID); returns undefined
What is going on ???
Note: styles is loaded via AJAX call (JSON result).
You might have to rework how you handle things in your controller but you can change your model to this:
<select data-ng-model="selectedStyle"
data-ng-options="s as s.StyleName for s in styles"
data-ng-change="GetOptions()">
<option value="">--Select Style--</option>
</select>
Then in your controller, you can do this
$scope.GetOptions = function(){
console.log($scope.selectedStyle.EncryptedValue)
};
The only thing is now if you want to reference your StyleId you have to do it this way:
$scope.selectedStyle.StyleId
I have a problem updating <select> with ng-init.
HTML:
<form data-ng-init="showStudent()">
<select id="studbranch" data-ng-model="student.branch"
data-ng-options="obj.name for obj in branches track by obj.id" required>
<option value="">-- Select Branch --</option>
</select>
</form>
Outputs:
<option value="">-- Select Branch --</option>
<option value="1">Branch 1</option>
<option value="2">Branch 2</option>
<option value="3">Branch 3</option>
In JS file:
$scope.branches = [{"id":"1","name":"Branch 1"},{"id":"2","name":"Branch 2"},{"id":"3","name":"Branch 3"}];
$scope.showStudent = function() {
$.getJSON('student.php', function(data) {
$scope.student = data[0]; $scope.$apply();
alert($scope.student.branch);
});
}
On page load (init), it alerts 3. That means student.branch is set to 3. But the select is not updated. It stays at default value. What could be wrong? Are the select values set after init?
If I add $('#studbranch').val($scope.student.branch); after the alert() it works fine.
Please try do that in angular way not jQuery
app.controller(function($scope, $http){
...
$scope.student = [];
$scope.showStudent = function() {
$http.get('student.php').then( function(data) {
angular.copy(data[0], $scope.student);
alert($scope.student.branch);
});
};
...
}
Your ng-options should be formatted like so:
data-ng-options="obj.id as obj.name for obj in branches track by obj.id"
Assigning the ng-model of the select to the right id will now update the select.
<select onchange="showResult(this.value)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
In above code, the value of each <option> has been passed as parameter in showResult().
My questions is how to pass the content of option element (i.e.'London','France', 'Berlin', 'Rome') as parameter in showResult().
Many Thanks
[yourselect].options[0].text returns 'London', [yourselect].options[1].text France, etc. So, in other words, for every option of an options-nodeList the property text contains its content.
write this code
<select onchange="showResult(this.options[this.selectedIndex])">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>
so you will pass the whole selected option node to the showResult function and you will be able to access both the value and text
function showResult(opt) {
alert(opt.value); /* e.g. DDD */
alert(opt.text); /* e.g. Rome */
}
Example Fiddle : http://jsfiddle.net/xypGa/
Try this.options[this.selectedIndex].text, been a while since I did this without jQuery.
function showResult()
{
var value = this.options[this.selectedIndex].value;
var content = this.options[this.selectedIndex].text;
}
Is this question about your issue - Get selected value in dropdown list using JavaScript? ?
in general - document.FORM.FIELDMANE.options[document.FORM.FIELDMANE.selectedIndex].value
in your case it should be i suppose - onchange="showResult(this.options[this.selectedIndex].value)
Instead of passing this.value (the value property of the select element), pass this (the select element), i.e. onchange="showResult(this)", and use code like
function showResult(selectElem) {
var optionText = selectElem.options[selectElem.selectedIndex].text;
alert(optionText); // replace by real code that uses the string
}
An added advantage is that now the function has access to the entire element, so that if you later need to use the value property, too, in the function, you can do that without modifying the function calls.
<select onchange="showResult(this.options[this.selectedIndex].text)">
<option value="AAA">London</option>
<option value="BBB">France</option>
<option value="ccc">Berlin</option>
<option value="DDD">Rome</option>
</select>