I'm trying to get a select box appear for a bunch of data extra which is selected using a <select> box like so:
{{view "select" content=banks
optionLabelPath="content.name"
optionValuePath="content._id"
selection="content._id"
value=data.bank}}
And I'm populating banks like so:
var AccountsEditController = Ember.ObjectController.extend({
banks : [],
init : function(){
this._super();
var self = this;
Ember.$.getJSON("/admin_api/banks", function(rsp){
self.set("banks", rsp.data);
});
},
// ...
});
However, when the banks gets updated, a previous value for data.bank isn't selected, which means pressing save produces a incorrect result. Also the value seems to reset to null on the actual data binding. I'm also not too sure if the way I'm populating the data is correct (I don't wish to use Ember Data).
Related
Background
Google App Maker has a Multi Select Widget which allows the user to select several options from a list.
Current State
By default, all options are unselected and the user must manually select all desired options.
Desired State
I would like to programatically cause all options to be selected so that the user can manually deselect all undesired options.
What I've Tried
App Maker Documentation:
The Multi Select Widget documentation provides information about how to bind options and values, but does not provide an option for pre-selecting these options.
Javascript onAttach Event and onDataLoad Event:
I attempted to run Javascript to programatically select the options but think this is where I'm coming undone.
The options in my Multi Select Widget are bound to #datasources.Suppliers.items..Supplier_Name and all options are displayed in the widget correctly.
I can successfully hard-code the options to be programatically selected, e.g.:
var optionsToBeProgramaticallySelected = ["Option1", "Option2", "Option3"];
widget.values = optionsToBeProgramaticallySelected;
... however, I do not want to hard-code the values to be selected because these will change over time. Therefore, I attempted to programatically create an array of all options and use that as the list of options to be programatically selected. However, I was not able to successfully return the array for use. The code I used to attempt this is:
var listOfAllPossibleOptions = app.datasources.Suppliers.items.concat();
widget.values = listOfAllPossibleOptions;
Question
How can I cause my Multi Select Widget to select all options?
Perhaps try querying the Suppliers datasource (on the server side), getting the results into an array.
Your client side function (multi select widget is passed on as parameter):
function querySuppliers(MultiSelectWidget){
google.script.run
.withFailureHandler(function() {
alert("Unable to query suppliers");
})
.withSuccessHandler(function(result) {//this is the return value from server side
MultiSelectWidget.values = result;
})
.querySuppliers();
}
Your server side function:
function querySuppliers(){
var suppliersDS = app.models.Suppliers.newQuery();//new query to datasource
var suppliers = suppliersDS.run();//run the query
var returnArray = [];//array to store suppliers
for (i=0; i<suppliers.length; i++) {//traverse through suppliers to grab names
returnArray.push(suppliers[i].Supplier_Name);
}
return returnArray;
}
I have a mongoDB with a DB = Staff and a collection = records. It contains a list of employees, and one of the fields is workgroup and it has items like "management", "union", "support staff", etc.
I want to populate a dropdown list with the values of the workgroup field and then use it to retrieve all records from the specified value selected in the dropdown.
I am using Ruby and I can retrieve the values ok (I can see them in the console), but they do not populate the dropdown list.
This is my Ruby statement:
get '/workgroup' do
Record.all.to_a.collect(&:workgroup).uniq.to_json
end
My attempt at the javascript is:
<script>
//var json = 'http://localhost:4567/api/v1/workgroup';
$(document).ready(function()
{
$.getJSON("/api/v1/workgroup",function(obj)
{
$.each(json.records,function(key,value)
{
var option = $('<option />').val(value.workgroup);
$("#dropDownDest").append(option);
})
})
});
</script>
Once I get the information in the dropdown, I want to use it to return all records with that workgroup value to a table. I haven't figured that part out yet. One step at a time!
Thanks!!
Within your $.getJSON call back you are referencing json.records, but there is no json variable or object.
The argument you are passing to the callback is obj. I think you really want to be doing $.each(obj, function(key, value)...
I got a question and I am also accepting to getting downvotes for this because I have not really tried something yet. The problem is I don't know how to name the problem and for what I should look for around the internet.
It's like this, I got a link to an api which (in my case) contains all provinces of china in this format:
{
"result":{
"version":"1.0",
"status":100101,
"msg":"got provinces successfully"
},
"data":[
{"province":"\u9999\u6e2f"},
{"province":"\u5317\u4eac\u5e02"}
and some more. Now I want to make a dropdown select menu which contains all this provinces as dropdown values and if one dropdown is selected it should check another URL which says if the selected province is valid or not (in my case it only can be valid because the user cannot enter something himself)
?action=api&i=getCityForProvince&data=北京市
This would be the url for checking this, if it is successful it shows me the cities of the province in the same format like the code above. With this i want to make another select box which only appears if the first is true. In this select box you then select your city and that's it.
I sadly have absolutely no idea how to start with this problem and for what i should look for to solve this.
I wonder if the fact that it's chinese has anything to do with your problem? I bet, it doesn't. With jquery it's pretty easy to accomplish such tasks. It's like building blocks you need to put together.
Learn how to make ajax calls with JQuery. It's quite easy, also it should process your Json result, making it a object or array. So in the callback, you can build up your select box like described here. Another block is to bind to the change event of the select box, which is doing another Ajax call (you already know that now) using the value from the Select input. And in the result of that callback, you can also check the result json and if the result was successful, you can easily fill up another select box using already known methods now, or change its visiblity according to your results.
I think you will want to learn those things, and was not supposed to get a ready coded solution :)
To make your work easier, I recommend you to use:
a template library
an MVVM framework
The difference between using jQuery directly and an MVVM library, or template library, like handlebars or mustache, is that with jQuery you have to take care of handling the elements, and with the other solutions, you leave this work to the framework.
ANyway, I recommend using knockout over using the template libraries, because:
it includes the templates
it can provide a two-way binding
it can handle events
it can apply classes, modify visibility, enable and disable elements...
Here I add a simple example of what it can do:
// This is the ko part:
// This is the view model using Revealing Module Pattern to build it
var vm = (function(){
// The list of provinces which will be shown when available
var provinces = ko.observableArray([]);
// The province selected in the list
var selectedProvince = ko.observable();
// This is what you'd call when the provinces are loaded using AJAX
var loadProvinces = function(data) {
provinces(data);
};
// This functions will be triggered when the selected province changes...
var updateCities = function() {
console.log("Here you'd update cities");
};
// ... because of this subscription
selectedProvince.subscribe(updateCities);
// return the object with the desired properties:
return {
provinces: provinces,
selectedProvince: selectedProvince,
loadProvinces: loadProvinces,
updateCities: updateCities
};
})();
ko.applyBindings(vm);
// AJAX call simulation:
// the returned data
var data = [
{"province":"\u9999\u6e2f"},
{"province":"\u5317\u4eac\u5e02"}
];
// a time out to load the data (simulate AJAX call)
setTimeout(function() { vm.loadProvinces(data);}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="visible: !(provinces().length)">
Please wait while loading provinces
</div>
<div data-bind="visible: provinces().length">
<select data-bind="options: provinces,
optionsText: 'province',
optionsValue: 'province',
value: selectedProvince">
</select>
<p>Selected province: <span data-bind="text: selectedProvince"></span></p>
</div>
As you can see, it handles not only creating the DOM elements, bu also handling events, two way-bindig, detecting changes in values...
You could originally write the HTML for your second checkbox and give it a display: none; property. Then on the JS:
if (firstcheckboxValue === true) {
document.getElementById('secondCheckboxId').style='display: block';
}
You could use display: inline-block; or display: inline; etc, whatever suits your layout better.
Things would drastically get easier if you used jQuery. Since there's no code to start working with, I'll just list out steps I'd go through.
1) Write DOM elements for dropdowns, say #dd_provinces #dd_cities. #dd_cities would be hidden.
2) From $().ready(function(){...}) I'd make the web API call.
3) From result callback of the API call in #2, make the second API call(one to fetch cities of the province).
4) Result callback of the second API callback will populate the DOM element #dd_cities
5) Unhide #dd_cities
Sample code:
HTML
<select id="dd_provinces">
</select>
<select id="dd_cities" style="visibility: hidden">
</select>
JS
$(document).ready(function() {
$.ajax({
url: "/echo/json/",
data: "",
success: function(evt) {
var mData = ["City 1", "City 2", "City 3", "City 4"];
for(var i = 0; i < mData.length; i++){
var optionElem = "<option>" + mData[i] + "</option>";
$("#dd_provinces").append(optionElem);
}
$.ajax({
url: "/echo/json",
data: "",
success: function(evt) {
$("#dd_cities").css("visibility", "visible").animate('5000');
}
});
},
error: function(evt) {
console.log(evt);
}
});
});
I have the following issue with angular and the html select-input:
When the user loads the page my select is empty until the data is loaded and returned from the corresponding service.
In this case the select is populated correctly.
However, the user should be able to filter the model with a click on a button.
When I press the button a new request is send to the REST-API and the response contains the new model for the select.
Unfortunately, the select won't update correctly even when I change it's model
Here is some code to illustrate my problem:
// This happens in my controller
EventService.getAvailableRooms(requestObject).then(function successCallback(response){
// sanatizeRoomTypes is used to generate user-friendly names instead of [1, 2,..]
vm.rooms = DataSanatizer.sanatizeRoomTypes(response.data);
}, function errorCallback(response){
console.log(response)
});
vm.rooms is the model of my select:
<select id="roomSelect" ng-model="eventCtrl.selectedRooms"
ng-options="room.name group by room.type for room in eventCtrl.rooms track by room.id" multiple required>
</select>
In some cases the select duplicates it's model or looses entries. It seems like there is some sort of data binding problem.
Thanks,
Try wrapping your model changes in $scope.apply :
$scope.$apply(function() {
$scope.data.myVar = "Another value";
});
Read here for more info:
http://tutorials.jenkov.com/angularjs/watch-digest-apply.html
You can also use $scope.$watch on the changing $scope variables to update them in your view.
So I have a date picker and a select-list. Then a jqgrid, working fine, filtering and all. This is what I am doing.
$("#sessSearch").unbind('click').on('click', function(){
var mydate = $("#sessSelector").val();
var mytype = $("#sess_type :selected").val();
if(mydate && mytype){
$("#listSESS").jqGrid('setGridParam',{postData:{sess_date:mydate, sess_type:mytype}}).trigger("reloadGrid");
}else{
alert("The search form is incomplete");
}
$("#sessSelector").val('');
$("#sess_type").val('');
});
What is happening there is I am sending along the values of my selectlist and datepicker along in the postData for the jqgrid. Only when the search button is clicked. So far so good. I can get the values on the serverside. The problem is when I click the refresh button on the grid pager, the previously sent paramiters remain in the postData. See below, firebug showing all post parameters.
The first is a normal default load, works fine.
The second happens after using my search form and adding to the postData and then I clicked on the refresh button the grid pager.
How do I reset the postData for the grid native reload mechanism to exclude my custom parameters?
My custom paramiters must only go in when I tell it to go in.
Please advise.
You can use getGridParam to get reference on internal object postData. The object have properties sess_date and sess_type with the values from the last setGridParam call. One can use delete to remove property from an object. So the following code should work
var postData = $("#listSESS").jqGrid("getGridParam", "postData");
delete postData.sess_date;
delete postData.sess_type;
Thank you so much Oleg, I basically disabled the default refresh action and did this with the pager. So my custom search sends the parameters only when my search mutton is clicked.
jQuery("#listSESS").jqGrid('navGrid','#pagerSESS',{edit:false,add:false,del:false,search:false, refresh:false},
{}, // edit options
{}, // add options
{}, // del options
{} // search options
);
$("#listSESS").jqGrid('navButtonAdd', "#pagerSESS", {
caption: "", title: "Reload Grid", buttonicon: "ui-icon-refresh",
onClickButton: function () {
var mypostData = $("#listSESS").jqGrid("getGridParam", "postData");
delete mypostData.sess_date;
delete mypostData.sess_type;
$("#listSESS").jqGrid('setGridParam',{postData:mypostData}).trigger("reloadGrid");
}
});
works like a charm.