I have a select box, defined as follows:
<select ng-model="selectedSupplier" ng-options="supplier.name for supplier in suppliers">
</select>
IN my controller, I have the a button which, although not doing anything useful, serves to explain a problem I'm having changing the selected value in the controller:
When this function is executed, the options in the select box are set, and the selected option is set:
$scope.foo = function() {
var foos = [{"id":1,"name":"No 1"},{"id":2,"name":"No 2"},{"id":3,"name":"No 3"},{"id":4,"name":"No 4"}];
$scope.suppliers = foos;
$scope.selectedSupplier = foos[2];
}
But I changed the function to be like this, it still sets the options, but the selected option is a new blank option, none of my defined ones:
$scope.foo = function() {
var foos = [{"id":1,"name":"No 1"},{"id":2,"name":"No 2"},{"id":3,"name":"No 3"},{"id":4,"name":"No 4"}];
$scope.suppliers = foos;
$scope.selectedSupplier = {"id":3,"name":"No 3"};
}
What's going on here? How can I set the selected option using an object other than the original?
This is an equality/identity issue. The literal
$scope.selectedSupplier = {"id":3,"name":"No 3"};
Is not the same as the object in your foos array. Although they contain the same data, they are 2 different references.
$scope.selectedSupplier === foos[2] // false
You correctly reference the object in your array in your first example.
$scope.selectedSupplier = foos[2];
ngOptions directive handles arrays and objects differently: https://docs.angularjs.org/api/ng/directive/ngOptions
In this line:
$scope.selectedSupplier = {"id":3,"name":"No 3"};
You are assigning an independant object into $scope.selectedSupplier, which is not part of the options list. There is no deep comparison behind the scenes - in case of complex objects, you must assign the actual object itself.
If you want for example to assign selected value based on the id property, have such code:
var idToAssign = 2;
for (var i = 0; i < $scope.suppliers.length; i++) {
var curSupplier = $scope.suppliers[i];
if (curSupplier.id == idToAssign) {
$scope.selectedSupplier = curSupplier;
break;
}
}
I tried it with removing " around object keys (id not "id") as it is not required in javascript and it worked.
$scope.foo = function() {
var foos = [{id:1,name:"No 1"},{id:2,name:"No 2"},{id:3,name:"No 3"},{id:4,name:"No 4"}];
$scope.suppliers = foos;
$scope.selectedSupplier = {id:3,name:"No 3"};
};
if you have no issue removing quotes then it can be a solution
Related
I am attemtping to add strings together to create the name of a variable, which I can then check its value. The code may explain this better, to understand what I mean.
I have several variables like below
var scList = ["stream", "dev", "web"];
var stream_sc = ["test0", "test1"];
var dev_sc = ["value","value"];
var web_sc = ["value", "value"];
In another function I am checking if entered text matches one of the values in scList, I then hope to add the string "_sc" to the end of the entered text, and from there be able to display the values inside the variables ending in _sc. The below is what I have so far. (With dataAr[1] being the user entered string I am checking for)
for (var i = 0; i < scList.length; i++) {
if (dataAr[1] == scList[i]) {
window.alert(scList[i]+"_sc"[0]);
}
}
While it is able to match the string to a value in the scList Array properly, the value returned by the window alert is just the user entered string, not showing the "_sc", which makes sense but how could I get this to then relate to the matching variable ending in "_sc"?
To Clarify
My hope is that if a user entered "stream" or if dataAr[1] == "stream" that the returned value would be "test0" from stream_sc[0]
Thank you for any help!
You have an extraneous [0] after "_sc" which would grab the underscore and append it to the variable name. What you want is probably scList[i] + "_sc"
You should store them in a json object, so you can reference the sc names to retrieve the values, like so:
const varMap = {
"stream_sc": [ ],
"dev_sc": [ ],
"web_sc": [ ]
};
// access the map using the entered value
varMap[scList[i] + "_sc"][j]
// where j would be the desired item index in the _sc array
I'm currently on a phone, so I hope the formatting comes out ok.
EDIT: fixed some syntax that was needed that the asker pointed out.
I assume you dataAR is an array as you make a reference to a key in the conditional dataAr[1]. You could use .includes() in that case to see if your array includes the value of scList[i]... I used a select to show how this could be achieved in a for loop and conditional. If the conditional is true, then rather that using the array scList[i] value use the value that is true... Then concatenate the _sc onto the value and define that as a new variable...
var sel = document.getElementById('sel');
var dataAr = ['gaming']; // array with a value that is not true present already
var scList = ["stream", "dev", "web"];
var stream_sc = ["test0", "test1"];
var dev_sc = ["value", "value"];
var web_sc = ["value", "value"];
function getVal(scList, sel) {
for (var i = 0; i < scList.length; i++) {
if (scList.includes(sel.value)) {
val = sel.value + '_sc';
return val;
}
}
}
let val;
sel.addEventListener("change", function(e) {
dataAr.push(sel.value);
alert(getVal(scList, sel));
// val myVar = getVal(scList, sel); <-- Do something with this var now
});
<select name="sel" id="sel">
<option>--select an option below--</option>
<option value="stream">Twitch</option>
<option value="dev">Visual Studio Code</option>
<option value="web">Mozilla</option>
</select>
I'm using Kendo multi select as follow but i can't get selected values
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
for (var itm in items)
{
selectedData.push(itm);
}
but array selectedData return indices of items in multiselect not values .
You can also assign the array, returned from the value() method, directly to the variable, e.g.:
var ms = $("#multiselect").kendoMultiSelect({
value: ["1", "2"]
}).data('kendoMultiSelect');
var selectedItems = ms.value();
console.log(selectedItems); // ["1", "2"]
Use this other one returns indices.
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
for (var i=0;i<items.length;i++)
{
selectedData.push(items[i]);
}
Your original code doesn't look wrong. Are you sure you are getting only indices? Perhaps you should post your MultiSelect code as well. I found this question because I had the same problem and used the other answers for reference, but I found them overcomplicated. So let me answer in another complicated way :)
Here's what I've got. I know it's more code than you need, but I think it's important to see the full picture here. First let me set this up. There's a problem with the Kendo().MultiSelect.Name("SomeName") property if you are using it more than once. "Name" sets not only the html name, but the id as well, and you never want two ids with the same identifier. So in my code, I am appending a unique Id to my MultiSelect.Name property to ensure a unique id. I am putting the MultiSelect in each row of a table of people. I am showing this to make sure you are using the DataValueField property so you are able to get the selected values (not the text you see in the ui). If you are just showing a list of text values with no id behind them, perhaps that is why you are getting the wrong data?
#foreach (var cm in Model.CaseMembers)
{
<tr>
<td>
#(Html.Kendo().MultiSelect()
.Name("IsDelegateFor" + cm.CaseMemberId)
.Placeholder("is a delegate for..")
.DataTextField("FullName")
.DataValueField("CaseMemberId")
.BindTo(Model.Attorneys)
)
</td>
</tr>
}
then, later on, in my jQuery where I attempt to extract out the DataValueField (CaseMemberId), which is the array of selected values of the MultiSelect...
var sRows = [];
$('#cmGrid tr').each(function () {
// 'this' is a tr
$tr = $(this);
// create an object that will hold my array of selected values (and other stuff)
var rec = {};
rec.IsADelegateFor = [];
// loop over all tds in current row
$('td', $tr).each(function (colIndex, col) {
if (colIndex === 3) {
// make sure our MultiSelect exists in this td
if ($(this).find("#IsDelegateFor" + rec.CaseMemberId).length) {
// it exists, so grab the array of selected ids and assign to our record array
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
}
}
}
// add this tr to the collection
sRows.push(rec);
}
so this is all a super verbose way of saying that this single line, as the other people mentioned works perfectly to grab the ids. There is no need to iterate over the .value() array and push the contents to another array!
rec.IsADelegateFor = $(this).find("#IsDelegateFor" + rec.CaseMemberId).data("kendoMultiSelect").value();
So in your original code, there is no reason the following should not work,
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData = [];
selectedData = multiselect.value();
console.log(selectedData);
unless
you don't have your MultiSelect set up properly in C# with DataValueField
you have multiple MultiSelects on the page with the exact same id and it's reading from a different one than you think.
You don't even have value fields, just a list of text.
var selected = $("#multi").data("kendoMultiSelect").value();
The solution given by volvox works.
Below is jquery version,
var multiselect = $("#SelectRoles").data("kendoMultiSelect");
var selectedData= [];
var items = multiselect.value();
$.each(items ,function(i,v){
selectedData.push(v);
});
Im using the following code,
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
aSelectedDataSet.push(fnCreateEnt(aProp, oData, oPushedObject));
});
This is aSelectedDataSet values
and this is the values of OData
What I need is that before I do the push is to fill the listTypeGroup & listTypeGroupDescription (with the red arrow ) with values that Are inside the oData -> ListTypeGroupAssigment -> result (listTypeGroup & listTypeGroupDescription) , The index is relevant since I want to add just the value of the index in each iteration (since this code is called inside outer loop and the index determine the current step of the loop) ,How it can be done nicely?
The result contain 100 entries (always) and the a selected data will have 100 entries at the end...
Update :)
Just to be clear In the pic I show the values which is hardcoded for this run but the values can be any values, we just need to find the match between the both objects values...
I mean to find a match between to_ListTypeGroupAssigment in both object (which in this case exist ) and if in oData there is result bigger then one entry start with the matching ...
UPDATE2 - when I try Dave code the following happen for each entry,
This happen in the Jquery.extend line...any idea how to overcome this?
The following hard-coded of Dave:-) work perfect but I need generic code which doesnt refer to specific field name
jQuery.each(aDataSet, function(index, oData) {
oPushedObject = {};
fnCreatePushedEntry(aProperties, oData, oPushedObject);
var result = oData.to_ListTypeGroupAssignment.results[index];
oPushedObject.to_ListTypeGroupAssignment = {
ListTypeGroup: result.ListTypeGroup,
ListTypeGroupDescription: result.ListTypeGroupDescription
};
aSelectedDataSet.push(oPushedObject);
});
Im stuck :(any idea how to proceed here ?what can be wrong with the extend ?
should I use something else ? Im new to jQuery...:)
I think that this happen(in Dave answer) because the oData[key] is contain the results and not the specified key (the keyValue = to_ListTypeGroupAssignment ) which is correct but we need the value inside the object result per index...
var needValuesForMatch = {
ListTypeGroup: 'undefined',
ListTypeGroupDescription: 'undefined',
}
//Just to show that oPushedObject can contain additional values just for simulation
var temp = {
test: 1
};
//------------------This object to_ListTypeGroupAssigment should be filled (in generic way :) ------
var oPushedObject = {
temp: temp,
to_ListTypeGroupAssignment: needValuesForMatch
};
oPushedObject is one instance in aSelectedDataSet
and after the matching I need to do the follwing:
aSelectedDataSet.push(oPushedObject);
Is this what you're after:
OPTION ONE - DEEP CLONE FROM oData TO aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
var objectToClone = oData[childObject]['results'][index];
if(objectToClone)
$.extend(true,currentObject[childObject],objectToClone);
}
});
Here is your data in a fiddle with the function applied: https://jsfiddle.net/hyz0s5fe/
OPTION TWO - DEEP CLONE FROM oData ONLY WHERE PROPERTY EXISTS IN aSelectedDataSet
aSelectedDataSet.forEach(function(currentObject,index){
for (var childObject in currentObject) {
if (! currentObject.hasOwnProperty(childObject))
continue;
if(typeof currentObject[childObject] !== 'object')
continue;
for(var grandChildObject in currentObject[childObject]) {
var objectToClone = oData[childObject]['results'][index][grandChildObject];
if(typeof objectToClone === 'object') {
$.extend(true,currentObject[childObject][grandChildObject],objectToClone);
} else {
currentObject[childObject][grandChildObject] = objectToClone;
}
}
}
Fiddle for option 2: https://jsfiddle.net/4rh6tt25/
If I am understanding you correctly this should just be a small change:
jQuery.each(aDataSel, function(index, oData) {
oPushedObject = {};
fnCreateEnt(aProp, oData, oPushObj);
//get all the properties of oData and clone into matching properties of oPushObj
Object.getOwnPropertyNames(oData).forEach(function(key) {
if (oPushObj.hasOwnProperty(key)) {
//oPushObj has a matching property, start creating destination object
oPushObj[key] = {};
var source = oData[key];
var destination = oPushObj[key];
//can safely assume we are copying an object. iterate through source properties
Object.getOwnPropertyNames(source).forEach(function(sourceKey) {
var sourceItem = source[sourceKey];
//handle property differently for arrays
if (Array.isArray(sourceItem)) {
//just copy the array item from the appropriate index
destination[sourceKey] = sourceItem.slice(index, index + 1);
} else {
//use jQuery to make a full clone of sourceItem
destination[sourceKey] = $.extend(true, {}, sourceItem);
}
});
}
});
aSelectedDataSet.push(oPushedObject);
});
It is unclear what exactly your fnCreateEnt() function returns though. I am assuming it is the populated oPushObj but it's not entirely clear from your question.
I keep having issues iterating over some JSON to put in select options
(btw, ignore the actual values for "label", those are garbage atm).
Here is an example that my php is passing into this:
[{"value":"1","label":"04-22-12"},{"value":"4","label":"04\/04\/12"}]
I am currently trying this loop:
*note, dateSelect is defined somewhere else
for (res in JSON.parse(request.responseText)) {
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
However, it is adding "undefined" into my options...
How do I get it so each value and corresponding label is put in there correctly?
You have an Array, so don't for-in.
In your code, res is the property name (the index of the Array in this case) in the form of a string, so the properties you're looking for aren't going to be defined on the string.
Do it like this...
for (var i = 0, parsed = JSON.parse(request.responseText); i < parsed.length; i++) {
var res = parsed[i];
var date = document.createElement("option");
date.value = res.value;
date.text = res.label;
dateSelect.add(date, null);
}
This is annoying me.
I'm setting an array in beginning of the doc:
var idPartner;
var myar = new Array();
myar[0] = "http://example.com/"+idPartner;
And I'm getting a number over the address, which is the id of partner. Great. But I'm trying to set it without success:
$.address.change(function(event) {
idPartner = 3;
alert(idPartner);
}
Ok. The alert is giving me the right number, but isn't setting it.
What's wrong?
Changing the value of the variable does not re-set the values within the array. That is just something javascript can't do automatically. You would have to re-generate the array for it to have the new id. Could you add the id to the value where you use the array instead of pre-setting the values in the array containing the id?
Edit: For example, you would do:
var myArray = [];
var myId = 0;
myArray[0] = "http://foo.com/id/";
and when you need to use a value from the array, you would do this:
var theVal = myArray[0] + myId;
Try this:
var myvar = ["http://site.com/"];
$.address.change(function(event) {
myvar[1] = 3;
}
then use myvar.join () where you need the full url.
The problem here is that at the line
myar[0] = "http://site.com/"+idPartner;
..you perform a string concatenation, meaning you copy the resulting string into the array at index position 0.
Hence, when later setting idPartnerit won't have any effect on the previously copied string. To avoid such effect you can either always construct the string again when the idPartnervariable updates or you create an object and you evaluate it when you need it like...
var MyObject = function(){
this.idPartner = 0; //default value
};
MyObject.prototype.getUrl = function(){
return "http://site.com/" + this.idPartner;
};
In this way you could use it like
var myGlblUrlObj = new MyObject();
$.address.change(function(event){
myGlblUrlObj.idPartner = ... /setting it here
});
at some later point you can then always get the correct url using
myGlblUrlObj.getUrl();
Now obviously it depends on the complexity of your situation. Maybe the suggested array solution might work as well, although I prefer having it encapsulated somewhere in an object for better reusability.
myar[0] = "http://site.com/" + idPartner;
After this line, myar[0] = "http://site.com/undefined" and it has nothing to do with the variable idPartner no more.
So, after that changing the value of idPartner will affect the value of myar[0].
You need to change the value of myar[0] itself.