Well, I guess I am encountering a bit of an issue again here. I will explain what I am trying to do.
I have a teammembers template in which I want to show Team Members & their specific information from a specific team. For that I have to join 3 tables.
This query should give you an idea:
SELECT *
FROM teams_members tm
inner join members m on tm.members_member_id=m.id
inner join teams t on tm.team_team_id=t.id
WHERE
t.team_name='Vancouver Canuck'
What I initially thought that I can make a simple array and simply do pushObject. But It's not working & and moreover, how would I show them?
Here's what I tried:
App.Model = Ember.Object.extend({});
App.TeammembersController = Ember.ObjectController.extend({
teammembers : [], //This is for getTeamMembers Action, Coming as undefined
selectedTeam : null,
team : function() {
var teams = [];
$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
}
});
return teams;
}.property(),
actions : {
getTeamMembers : function() {
teamName = this.get('selectedTeam.team_name');
data = {
team_name : this.get('selectedTeam.team_name'),
};
if (!Ember.isEmpty(teamName)) {
$.ajax({
type : "POST",
url : "http://pioneerdev.us/users/getTeamMembers",
data : data,
dataType : "json",
success : function(data) {
for (var i = 0; i < data.teammembers.length; i++) {
var teamNames = data.teammembers[i].firstname;
teammembers.pushObject(teamNames);
}
}
});
return teammembers;
console.log(teammembers);
} else {
}
}
}
});
I am getting teammember array as undefined in this. The snippet in actions will be responsible for spitting out Team Member's information when Team Name is selected from Ember.Select.
Thanks to https://stackoverflow.com/users/59272/christopher-swasey, I was able to re-use my snippet here:
<script type="text/x-handlebars" id="teammembers">
<div class="row">
<div class="span4">
<h4>Your Team Members</h4>
{{view Ember.Select
contentBinding="team"
optionValuePath="content.team_name"
optionLabelPath="content.team_name"
selectionBinding="selectedTeam"
prompt="Please Select a Team"}}
<button class="btn"
{{action 'getTeamMembers' bubbles=false }}>Get Team Members</button>
</div>
</div>
</script>
Moreover, what will user do, he will select the team from Ember.Select & when he clicks the button, somewhere I should be able to spit out team members & their information. In future, I might want to grab ids and delete them from server as well. How would I do that as well?
So, should I use custom views or is there some other way to do this?
There is an issue with the code that populates properties from ajax. For example the code of property team of App.TeammembersController does the following
1.initializes a local array variable teams
2.uses ajax to retrieve asynchronously the data from server
2.1.meanwhile the teams array within the ajax callback gets populated but never returned at the proper state of including data. It is required to set the controller's property once the teams array has been populated with the data. Then ember's binding will take care of the rest (populate controller's property, notify any other object interested, event the template to render the results)
3.and returns the empty teams array
So, you need to add two lines of code as follows,
team : function() {
var teams = [];
var self = this;/*<- */
$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
self.set("team",teams);/*<- */
}
});
return teams;
}.property()
The same should happen for the other properties you retrieve from ajax.
EDIT1
Below is an example based on your code. The code has been moved inside the IndexController and the button doing some action has been disabled for simplicity.
http://emberjs.jsbin.com/IbuHAgUB/1/edit
HBS
<script type="text/x-handlebars" data-template-name="index">
<div class="row">
<div class="span4">
<h4>Your Team Members</h4>
{{view Ember.Select
content=teams
optionValuePath="content.team_name"
optionLabelPath="content.team_name"
selection=selectedTeam
prompt="Please Select a Team"}}
<button class="btn"
{{action 'getTeamMembers' bubbles=false }} disabled>Get Team Members</button>
</div>
</div>
selected team:{{selectedTeam.team_name}}
</script>
JS
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.Model = Ember.Object.extend({});
App.IndexController = Ember.ObjectController.extend({
test:"lalal",
teammembers : [],
selectedTeam : null,
teams : function() {
//var teams = [];
var self = this;
/*$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
}
});*/
setTimeout(function(){
var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teams",data);
},1000);//mimic ajax call
return [];
}.property(),
actions : {
getTeamMembers : function() {
teamName = this.get('selectedTeam.team_name');
data = {
team_name : this.get('selectedTeam.team_name')
};
if (!Ember.isEmpty(teamName)) {
/*$.ajax({
type : "POST",
url : "http://pioneerdev.us/users/getTeamMembers",
data : data,
dataType : "json",
success : function(data) {
for (var i = 0; i < data.teammembers.length; i++) {
var teamNames = data.teammembers[i].firstname;
teammembers.pushObject(teamNames);
}
}
});*/
return teammembers;
} else {
}
}
}
});
The same concept can be followed to retrieve any data from the server and modify/delete it as well. Just have in mind that all requests are async and within the callback functions you should update your ember app model/data, then ember bindings do all the magic.
EDIT2
In order to show the team members in a separate view (based on last comments) once the team is selected, either by clicking the button or from another bound property you may request via ajax the members for the selected team id (unless you have already loaded them eagerly) you can render the property of teammembersinside an included view or partial. For instance the same example and when the button is pressed members appear (without logic hardcoded but async lazy loaded data),
http://emberjs.jsbin.com/IbuHAgUB/2/edit
HBS
<script type="text/x-handlebars" data-template-name="_members">
<i>this is a partial for members</i>
{{#each member in teammembers}}<br/>
{{member.firstName}}
{{/each}}
</script>
JS
App.IndexController = Ember.ObjectController.extend({
test:"lalal",
teammembers : [],
selectedTeam : null,
teams : function() {
var self = this;
setTimeout(function(){
var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teams",data);
},1000);//mimic ajax call
return [];
}.property(),
actions : {
getTeamMembers : function() {
var self = this;
setTimeout(function(){
var data = [{firstName:'member1'}, {firstName:'member2'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teammembers",data);
},1000);//mimic ajax call
}
}
});
Related
Delete Function:
My backbone function to delete a model (called on the click of a button) looks like this:
deleteCar: function (ev) {
console.log(this.car.toJSON());
this.car.destroy({
success: function () {
router.navigate('', {trigger:true});
}
});
return false;
},
this.car is created in another function but in the main scope. As seen above, I'm logging the contents of this.car and I get a JSON like this:
Object {carId: "17", carDes: "awesome"}
Now, I'm calling this.car.destroy... and I'm observing the network tab on Chrome. I can see a DELETE request firing but there is no data appended to the request. It's just an empty request to the correct url.
How can I attach my car model to the request?
Edit:
Render Function:
This is the function that creates a new car model. It is in the same Backbone view as the Delete function above.
render: function(options) {
var that = this;
if (options.id) {
that.car = new Car({
carId: options.id
});
that.car.url = 'http://localhost/Project/index.php/rest/resource/car/carId/' + options.id;
that.car.fetch({
success: function(car) {
console.log(that.car.toJSON());
that.car.url = 'http://localhost/Project/index.php/rest/resource/car/';
var template = _.template($("#edit-car-template").html());
var data = {
car: that.car
};
that.$el.html(template(data));
}
});
} else {
var template = _.template($("#edit-car-template").html());
var data = {
car: null
};
that.$el.html(template(data));
}
}
Edit-Car-Template
<script type="text/template" id="edit-car-template">
<form class="edit-car-form">
<legend>
<%= car ? 'Edit' : 'New' %> Car</legend>
<label>Car Description</label>
<input name="carDes" type="text" value="<%= car ? car.get('carDes') : '' %>">
<hr />
<button type="submit" class="btn">
<%= car ? 'Update' : 'Create' %>
</button>
<% if(car) { %>
<input type="hidden" name="carId" value="<%= car.get('carId') %>" />
<button data-car-id="<%= car.get('carId') %>" class="btn btn-danger delete">Delete</button>
<% }; %>
</form>
</script>
Edit 2:
Layout:
The view layout of my application is as follows:
And the following code is used to render the CarListView (get the list of cars using the REST API)
var CarListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
this.cars = new Cars();
this.cars.fetch({
success: function () {
var template = _.template($("#car-list-template").html());
var data = {cars: that.cars.toJSON()};
that.$el.html(template(data));
}
})
}
});
Models
My car model and car collection are defined as follows:
var Car = Backbone.Model.extend({
urlRoot: ROOT + 'car',
idAttribute: 'carId'
});
var Cars = Backbone.Collection.extend({
model: Car,
url: ROOT + 'car'
})
Update Function:
And following is the code for saving (updating) the model once the update button is clicked. This part works perfectly.
events: {
'submit .edit-car-form': 'saveCar',
'click .delete': 'deleteCar'
},
saveCar: function (ev) {
console.log('in save');
var carDetails = $(ev.currentTarget).serializeObject();
var car = new Car();
car.save(carDetails, {
success: function (car) {
router.navigate('', {trigger: true});
}
});
return false;
}
Sounds like this is working as intended. The Backbone.Model.destroy() method will generate an HTTP DELETE call to the model's the relevant URL. It typically won't have any content in the method body, as the ID at the end of the URL should be all you need to delete the RESTful resource. If you need different behavior, Backbone expects you to override the model's sync method (see here and here). Traditionally HTTP servers ignored any body sent on an HTTP DELETE method call, and the HTTP spec doesn't mention it needing a body, so Backbone is just encouraging you to follow that example.
Note also that setting the url property on the model instance itself is not the usual way to ensure the URL has the model ID. If you're going to use a Backbone.Model outside of a Backbone.Collection, you should include the urlRoot property when specifying Car ... where you can also specify the fetch function if you really need to override it:
var Car = Backbone.Model.extend({
urlRoot: '/Project/index.php/rest/resource/car`
fetch: function(options) {
// ... if needed, but note you can provide a "success"
// callback in the options; see below.
}
});
Doing it that way, Backbone will ensure that any call to car.destroy() will generate the right URL. For instance:
var car = new Car({
id: 123
});
// This will GET /Project/index.php/rest/resource/car/123
car.fetch({
success: function() {
console.log('Received: ' + car.toJSON());
// ... anything else you need to do after fetching.
});
});
// ... some time later ...
// This will DELETE /Project/index.php/rest/resource/car/123
car.destroy({
success: function() {
console.log('Car has been deleted on server');
}
});
Again, if your server needs more info than the model's ID to delete something, you'll have to override the sync method... but that's another question!
I am trying to implement a simple favorites system. On the page load posts are listed on the home page and any previously favorited posts called nubs will show up with the FAVED tag underneath them.
<div class="list-group" ng-repeat="nub in nubs">
<a href="#" class="list-group-item active">
<h4 class="list-group-item-heading">{{nub.title}}</h4>
<p class="list-group-item-text">{{nub.description}}</p>
<p class="list-group-item-text">{{nub.synopsis}}</p>
<li ng-repeat="url in nub.attachmentsUrls">
<p class="list-group-item-image">
<img ng-src={{url}} />
</p>
</li>
</a>
<button ng-click="toggleFav(nub)">favorite</button>
<p ng-show="getFaved(nub.$id)">FAVED</p>
</div>
This is working but when I add something to my favorites the page doesn't update to reflect the newly favorited post. I would like to make my page respond actively to the toggleFav function.
Here is my controller
var ref = new Firebase("https://xxxxx.firebaseio.com");
var auth = ref.getAuth();
var nubRef = new Firebase("https://xxxxx.firebaseio.com/Nubs");
var nubs = $firebaseArray(nubRef);
$scope.nubs = nubs;
var userRef = new Firebase("https://xxxxx.firebaseio.com/users");
var users = $firebaseArray(userRef);
$scope.users = users;
// Array of booleans for favorites
$scope.favedArray = [];
// Array of user ids for
$scope.userIdArray = [];
var userFavs = $firebaseArray(userRef.child(auth.uid).child("favorites"));
$scope.userFavs = userFavs;
userFavs.$loaded()
.then
(
function()
{
nubs.$loaded()
.then
(
function()
{
$scope.tempFaved = [];
$scope.tempId = [];
console.log(userFavs);
angular.forEach
(
nubs,
function(nub)
{
$scope.tempFaved.push(false);
$scope.tempId.push(nub.$id);
console.log($scope.tempId);
angular.forEach
(
userFavs,
function(favs)
{
console.log($scope.tempFaved);
if(favs.nub == nub.$id)
{
$scope.tempFaved.pop();
$scope.tempFaved.push(true);
console.log($scope.tempFaved);
}
}
);
}
);
while($scope.tempFaved.length > 0)
{
$scope.favedArray.push($scope.tempFaved.pop());
$scope.userIdArray.push($scope.tempId.pop());
}
$scope.getFaved = function(nubId)
{
console.log($scope.favedArray[$scope.userIdArray.indexOf(nubId)]);
$scope.faved = $scope.favedArray[$scope.userIdArray.indexOf(nubId)];
return $scope.faved;
}
$scope.toggleFav = function(nub)
{
var nubFavRef = nubRef.child(nub.$id).child("favorites");
var nubFavs = $firebaseArray(nubFavRef);
var faved = $scope.getFaved(nub.$id)
console.log(faved);
if (faved == false)
{
nubFavs.$add
(
{
user: auth.uid
}
);
userFavs.$add
(
{
nub: nub.$id
}
)
console.log("favorited");
}
else
{
nubFavs.$remove(auth.uid);
userFavs.$remove(nub.$id);
console.log("unfavorited");
}
};
}
)
}
);
Essentially it is looping through the nubs or posts displayed on the page and checking them against the nubs the user has favorited to display the FAVED tag and toggle the functionality of the favorite button. If the user doesn't have the nub favorited the button will add the nub to their list of favorites as well as adding them to the list of users that have the nub favorited and if the user does have the post favorited it will remove them.
The unfavorite functionality of the toggleFav doesn't work either so help with that would also be appreciated, but that's a matter of being able to access the right child of the faved arrays which I'm not sure how to do.
What I think needs to happen for the page to update with the right information when something is favorited is some kind of $on listener, but I'm not sure how to implement it.
/* How store data in fire base:
{
"home" : {
"room1" : {
"status" : "true",
"switch_name" : "light 2",
"user_id" : "-Kvbk-XHqluR-hB8l2Hh"
}
}
}
*/
//select element in which you want real time data.
const preObject = document.getElementById('tbl_switch_list');
//select your root table name
const dbRefObject = firebase.database().ref().child('home');
//Change Value in Firebase and view in your console.
dbRefObject.on('value',snap => console.log('Response : ',snap.val());
<h3>Switch List</h3>
<table id="tbl_switch_list" border="1">
<thead>
<tr>
<td>#ID</td>
<td>#switchName</td>
<td>#status</td>
</tr>
<thead>
<tbody id="list"></tbody>
</table>
I am new to Knockout and have been trying to follow code examples and the documentation, but keep running into an issue. My data bindings printing the Knockout observable function, not the actual values held by my observable fields. I can get the value if I evaluate the field using (), but if you do this you do not get any live data-binding / updates.
Below are some code snippets from my project that are directly related to the issue I am describing:
HTML
<div class="col-xs-6">
<div data-bind="foreach: leftColSocialAPIs">
<div class="social-metric">
<img data-bind="attr: { src: iconPath }" />
<strong data-bind="text: name"></strong>:
<span data-bind="text: totalCount"></span>
</div>
</div>
</div>
Note: leftColSocialAPIs contains an array of SocialAPIs. I can show that code too if needed.
Initializing the totalcount attribute
var SocialAPI = (function (_super) {
__extends(SocialAPI, _super);
function SocialAPI(json) {
_super.call(this, json);
this.totalCount = ko.observable(0);
this.templateName = "social-template";
}
SocialAPI.prototype.querySuccess = function () {
this.isLoaded(true);
appManager.increaseBadgeCount(this.totalCount());
ga('send', 'event', 'API Load', 'API Load - ' + this.name, appManager.getRedactedURL());
};
SocialAPI.prototype.toJSON = function () {
var self = this;
return {
name: self.name,
isActive: self.isActive(),
type: "social"
};
};
return SocialAPI;
})(API);
Updating totalcount attribute for LinkedIn
var LinkedIn = (function (_super) {
__extends(LinkedIn, _super);
function LinkedIn(json) {
json.name = "LinkedIn";
json.iconPath = "/images/icons/linkedin-16x16.png";
_super.call(this, json);
}
LinkedIn.prototype.queryData = function () {
this.isLoaded(false);
this.totalCount(0);
$.get("http://www.linkedin.com/countserv/count/share", { "url": appManager.getURL(), "format": "json" }, this.queryCallback.bind(this), "json").fail(this.queryFail.bind(this));
};
LinkedIn.prototype.queryCallback = function (results) {
if (results != undefined) {
results.count = parseInt(results.count);
this.totalCount(isNaN(results.count) ? 0 : results.count);
}
this.querySuccess();
};
return LinkedIn;
})(SocialAPI);
In the <span data-bind="text: totalCount"></span>, I expect to see a number ranging from 0-Integer.MAX. Instead I see the following:
As you can see, its outputting the knockout function itself, not the value of the function. Every code example I've seen, including those in the official documentation, says that I should be seeing the value, not the function. What am I doing wrong here? I can provide the full application code if needed.
Not sure, but KO view models obviously tend to bind own (not inherited through prototypes) observable properties only. So you should rewrite your code to supply totalCount observable for every social network separately.
I followed information on this answer
But it doesn't work in my situation.
Chrome Inspector console says "ReferenceError: dataResponse is not defined"
maybe that is the problem?
I am trying to GET this JSON from url:
[{"app_id":1,"app_name":"oh yeeah","app_description":"desc","app_price":111,"is_activated":false,"video":"videolink"},{"app_id":2,"app_name":"oh yeaaaeah","app_description":"ewaewq","app_price":222,"is_activated":false,"video":"fuck off"},{"app_id":3,"app_name":"oh yeaaaeah","app_description":"ewaewq","app_price":333,"is_activated":false,"video":"fuck off"}]
This is my javascript code
var appstore = angular.module('appstore', []);
appstore.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callbackFunc) {
$http({
method: 'GET',
url: '/administrator/components/com_apps/loadAppsJson.php'
}).success(function(data){
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
appstore.controller('app_Ctrl', function($scope, dataService) {
$scope.apps = [
{app_id:1, app_name:'oh yeah', app_description:'$app_description', app_price:111, is_activated:false, video:'$videolink'},
{app_id:2, app_name:'oh yeah', app_description:'$app_description', app_price:111, is_activated:false, video:'$videolink'},
{app_id:3, app_name:'oh yeah', app_description:'$app_description', app_price:111, is_activated:false, video:'$videolink'},
];
//$scope.apps = null;
dataService.getData(function(dataResponse) {
$scope.apps = dataResponse;
alert(dataResponse);
});
console.log(dataResponse);
console.log($scope.apps);
//get images thumbs
for(app = 0; app <= $scope.apps.length-1; app++) {
$scope.apps[app].thumb = ("000" + $scope.apps[app].app_id).slice(-3);
}
//separate apps to columns
var columns = [];
for (var i = 0; i < $scope.apps.length; i++ ) {
if (i % 3 == 0) columns.push([]);
columns[columns.length-1].push($scope.apps[i]);
}
$scope.columns = columns;
});
My HTML view
<div ng-controller="app_Ctrl">
<div class="row"></div>
<div class="row">
<div class="row" ng-repeat="apps in columns">
<div id="app_id_{{ app.app_id }}" class="col-lg-4" ng-repeat="app in apps | filter:search">
<div class="thumbnail" ng-class="app.is_activated ? 'activated' : ''">
<!-- -->
<img ng-src="/images/apps/app_images/{{ app.thumb }}_thumb.jpg" alt="{{ app.app_name }}" title="{{ app.app_name }}">
<div class="caption">
<h3>{{ app.app_name }}</h3>
<p class="app_price">{{ app.app_price }} €</p>
<div style="clear:both;"></div>
<p class="app_card_description">{{ app.app_description | limitTo:100 }}...</p>
Info
Video <span class="glyphicon glyphicon-facetime-video"></span>
{{ app.is_activated ? 'Aktivované' : 'Aktivovať' }}
</div>
</div>
</div>
</div>
To elaborate on what #Mritunjay said in the comments; review this code with comments:
dataService.getData(
// this is your callback function which has an argument for dataResponse
// the dataResponse variable will only be defined within the Call back function
function(dataResponse) {
$scope.apps = dataResponse;
alert(dataResponse);
// The Curly Brackets that follow mark the end of the callback handler method
});
// This log statement is not in the callback handler and there is no defined dataResponse variable which is probably why you got an error in the console
console.log(dataResponse);
You can fix this by moving the dataResponse log into the callback method, like this:
dataService.getData(function(dataResponse) {
$scope.apps = dataResponse;
alert(dataResponse);
console.log(dataResponse);
});
There appear to be other problems with your code, in that you are trying to access $scope.apps before the data is returned; which will hinder your processing. Easiest approach would be to move that processing into the result handler:
// define $scope.columns outside of the result handler
$scope.columns = [];
// call to method in service
dataService.getData(function(dataResponse) {
$scope.apps = dataResponse;
alert(dataResponse);
console.log(dataResponse);
// inside the result handler; you run this code after $scope.apps is defined:
for(app = 0; app <= $scope.apps.length-1; app++) {
$scope.apps[app].thumb = ("000" + $scope.apps[app].app_id).slice(-3);
}
//separate apps to columns
var columns = [];
for (var i = 0; i < $scope.apps.length; i++ ) {
if (i % 3 == 0) columns.push([]);
columns[columns.length-1].push($scope.apps[i]);
}
$scope.columns = columns;
});
That's what promises and asynchronous calls are all about.
console.log(dataResponse);
console.log($scope.apps);
The first one won't work because dataResource is a private variable and not part of the same scope you're trying to print.
The second one won't work either because that get's populated at future time (after X seconds), after the $http request is finished so it will only be availableat that point.
One way to do something after the object is populated is to use
$scope.$watch("apps", function (){
// do stuff
});
I have a page where a user can select if the transaction type is an inter accounts transfer, or a payment.
The model I pass in had two lists.
One is a list of SelectListItem
One is a list of SelectListItem
One of the lists is populated like this:
var entities = new EntityService().GetEntityListByPortfolio();
foreach (var entity in entities.Where(x=>x.EntityTypeId == (int)Constants.EntityTypes.BankAccount))
{
model.BankAccounts.Add(new SelectListItem
{
Value = entity.Id.ToString(CultureInfo.InvariantCulture),
Text = entity.Description
});
}
If the user selects 'Inter account transfer', I need to:
Populate DropdownA with the list from Accounts, and populate DropdownB with the same list of Accounts
If they select "Payment", then I need to change DrowdownB to a list of ThirdParty.
Is there a way, using javascript, to change the list sources, client side?
function changeDisplay() {
var id = $('.cmbType').val();
if (id == 1) // Payment
{
$('.lstSource'). ---- data from Model.ThirdParties
} else {
$('.lstSource'). ---- data from Model.Accounts
}
}
I'd prefer not to do a call back, as I want it to be quick.
You can load the options by jquery Code is Updated
Here is the code
You will get everything about Newton Json at http://json.codeplex.com/
C# CODE
//You need to import Newtonsoft.Json
string jsonA = JsonConvert.SerializeObject(ThirdParties);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringA = jsonA;
string jsonB = JsonConvert.SerializeObject(Accounts);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringB = jsonB;
You will get a jsonstring like this
[{"value":"1","text":"option 1"},{"value":"2","text":"option 2"},{"value":"3","text":"option 3"}]
HTML CODE
<button onclick="loadListA();">Load A</button>
<button onclick="loadListB();">Load B</button>
<select name="" id="items">
</select>
JavaScript Code
function option(value,text){
this.val= value;
this.text = text;
}
var listA=[];
var listB=[];
//you just have to fill the listA and listB by razor Code
//#foreach (var item in Model.ThirdParties)
//{
// <text>
// listA.push(new option('#item.Value', '#item.Text'));
// </text>
// }
//#foreach (var item in Model.Accounts)
// {
// <text>
// listA.push(new option('#item.Value', '#item.Text');
// </text>
// }
listA.push(new option(1,"a"));
listA.push(new option(2,"b"));
listA.push(new option(3,"c"));
listB.push(new option(4,"x"));
listB.push(new option(5,"y"));
listB.push(new option(6,"z"));
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
NEW Javascript Code fpor Json
var listA=[];
var listB=[];
var jsonStringA ='[{"val":"1","text":"option 1"},{"val":"2","text":"option 2"},{"value":"3","text":"option 3"}]';
var jsonStringB ='[{"val":"4","text":"option 4"},{"val":"5","text":"option 5"},{"value":"6","text":"option 6"}]';
//you just have to fill the listA and listB by razor Code
//var jsonStringA = '#Viewbag.jsonStringA';
//var jsonStringB = '#Viewbag.jsonStringB';
listA = JSON.parse(jsonStringA);
listB = JSON.parse(jsonStringB);
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
Here is the fiddle http://jsfiddle.net/pratbhoir/TF9m5/1/
See the new Jsfiddle for Json http://jsfiddle.net/pratbhoir/TF9m5/3/
ofcourse you can so that
try
var newOption = "<option value='"+"1"+'>Some Text</option>";
$(".lstSource").append(newOption);
or
$(".lstSource").append($("<option value='123'>Some Text</option>");
Or
$('.lstSource').
append($("<option></option>").
attr("value", "123").
text("Some Text"));
Link for reference
B default, I don't think the concept of "data-source" means something in html/javascript
Nevertheless, the solution you're looking for is something like knockoutjs
You'll be able to bind a viewmodel to any html element, then you will be able to change the data source of your DropDownList
see : http://knockoutjs.com/documentation/selectedOptions-binding.html