However, I want pass an "ID" into the option "value" field with a corresponding string as the option text.
So, if ID for Black = 1, White = 2, Blue = 3, then the html would look something like this:
<option value ='1'> Black </option>
This JSFiddle is similar to what I'm trying to accomplish:
http://jsfiddle.net/e6hzj8gx/4/
Except that I want to send only the value and use a key to call it.
I'm basically building a dropdown with Django that is dependent on what the user selects in another dropdown - there isn't really an elegant way of doing this in Django and it seems that serializing my data to json and then using javascript to build the drop down is the way to go.
My Django data is just a dict:
data = {1: 'Black', 2 = 'White', 3 = 'Blue'}
There are a few ways to loop through a javascript object. When working with a parsed JSON object, you can use:
for (var propName in obj) {
// access data using obj[propName]
}
In more complicated cases, you might have to check if the property isn't inherited from some other prototype using:
if (obj.hasOwnProperty(propName) { /* ... */ }
Furthermore, you can create DOM elements using document.createElement("option")
All together, it'll be something like this:
var obj = JSON.parse(serverData);
for (var propName in obj) {
var jsonValue = obj[propName];
if (jsonValue && (typeof jsonValue === "string")) {
var option = document.createElement("option");
option.value = propName;
option.innerText = jsonValue;
// Add created option to a select element
// ...
}
}
Let me know if I got your question right...
Related
$scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]
//Want to send model name + value of model Currently sending ngObject.MainObj.specificFormatObj
HTML
<select ng-model="ngObject.MainObj.specificFormatObj" ng-change="ngObject.MainObj.specificFormatObj">
<option></option>
<option ng-repeat="i in populateMap" value="{{i}}">{{i.name}}</option>
JS
// CONTROLLER CODE JSON parse object to get name and code GOT parsedObj
$scope.genericSetLookups=function (Obj) { // want to do something like get the ngmodel string + the value, currently only value comes in
Obj.code=parsedObj.code;
Obj.name=parsedObj.name
};
More Explanation: ngObject.MainObj.specificFormatObj
I want in my model to store value of lookups in a specific way, with name and code. On the UI I populate using ng-repeat , So when I select a particular value I can either take i.name as display and set value as i.code .
But if i do that my ngObject.MainObj.specificFormatObj.name will be null and the value will get set to ngObject.MainObj.specificFormatObj.code by using ng-model ,so that is the reason in value I am taking i, not i.code or i.value ,now in the map i have code and name pair.
I sent it to a function and parse it, and set the value to ngObject.MainObj.specificFormatObj.code=inputTofunc.code respectively for name. In this case in the ng-change i pass on the ngObject.MainObj.specificFormatObj.code ,rather i want to set i from the map to ngObject.MainObj.specificFormatObj send it to function also the model string which in this case would be "ngObject.MainObj.specificFormatObj" .
So for 10 lookups i can write a generic code ,where the model name and model value i can send as parameter to function and set it there, the above way am doing is probably hardcoding values which i want to set to model in a specific format.
Since you need to pass the model name as a parameter, pass it as a string like this from html :
ng-change="genericSetLookups('ngObject.SomeObject.abc',ngObject.SomeObject.abc)"
And in the controller as the model name contains "." we cannot use the name directly as the key. We need to parse the model name. I have cooked something up after searching a bit. Hope it works.
Controller code:
$scope.genericSetLookups(modelName, value){
Object.setValueByString($scope, modelName, value);
}
Object.setValueByString = function(o, s, val) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
if(i != n-1){
o = o[k];
}
else{
o[k] = val;
}
} else {
return;
}
}
return o;
}
Credit must also go to #Alnitak for the answer here
I didn't really understand your problem and the comments didn't make it clearer for me. What I tried to do is give you an example of how I would handle a select box and the model.
I would loop over the options with ng-options and show the selected option by putting {{selected.name}} in the template. Ofcourse if you would want to format the selected value in anyway or react to a change you can use ng-change.
Hope it helps.
Here is my JSFiddle
I'm not sure if I understood your question. If you want to save in your model the value code + name, maybe this code can help you:
<select ng-model="ngObject.MainObj.specificFormatObj" ng-options="(ppm.code + '-' + ppm.name) as ppm.name for ppm in populateMap">
</select>
jsfiddle
When I submit a form, one of the fields being submitted is an ID (number) instead of the name for easier processing by the server. Like so:
HTML dropdown select
<select ng-model="myColor" class="form-control"
ng-options = "color.ID as color.color for color in $parent.colorSelection">
</select>
AngularJS
$scope.colorSelection = [{"color": "Red", "ID": "7011"}, {"color": "Blue", "ID": "7012"}];
So the server sends a JSON back
res.json({
Color: req.query.color,
});
And now when I get the results back, I want to display the name instead of the ID number which is what the server sends back to me. So instead of showing "7011", I want to show "Red". How do I do this? Doing the following doesn't work.
{{results.Color.color}}
Since colorSelection is an array, you'll have to loop through it, directly or by using one of the array functions that does.
In this case, find is probably what you want (you may need a shim on older browsers, if Angular doesn't already shim it for you):
var entry = $scope.colorSelection.find(function(entry) { return entry.ID == results.Color.color; });
var color = entry && entry.color;
color will be either null (not found) or the color name.
It's a bit less clunky with ES2015:
let entry = $scope.colorSelection.find(entry => entry.ID == results.Color.color);
let color = entry && entry.color;
Another approach would be to have a reusable map of color IDs to names:
In ES5, you'd probably use an object:
// One-time initialization of the map, just after you create
// $scope.colorSelection
$scope.colorSelectionMap = Object.create(null);
$scope.colorSelection.forEach(function(entry) {
$scope.colorSelectionMap[entry.ID] = entry.color;
});
then
var color = $scope.colorSelectionMap[results.Color.color];
In ES2015, you could still do that, or you could use a Map:
// One-time initialization of the map, just after you create
// $scope.colorSelection
$scope.colorSelectionMap = new Map(
$scope.colorSelection.map(entry => [entry.ID, entry.color])
);
then
var color = $scope.colorSelectionMap.get(results.Color.color);
You need to use like below code for select
<select ng-model="myColor" class="form-control"
ng-options = "colorSelection as colorSelection.color for colorSelection in colorSelection ">
I want to create a select box from options stored in a variable (the values will change based on the user).
For now, I'm just trying to get it to work with this variable in my javascript file:
var resp = {"streams": [ {"sweet":"cookies"}, {"savory":"pizza"}]}
In the html file, I have a select id "selectedStream"
How do I invoke, both the select id from html and the variable from javascript to create the select box?
I've seen examples such as the one below, but I don't understand how to link the id and the variable to the box.
$("option:selected", myVar).text()
I hope this was coherent! Thanks
I think what you are trying to do is append option html nodes to an existing select element on your screen with an id of 'selectedStream'. You want to use the data from the 'resp' variable to populate the text and value of the option nodes that you are appending. If this is correct, I have implemented that functionality with this jsfiddle. The javascript is also below:
$(function(){
var resp = {"streams": [ {"sweet":"cookies", "savory":"pizza"}]};
var streamData = resp.streams[0];
var optionTemplate = "<option value=\"{0}\">{1}</option>";
for(var key in streamData){
var value = streamData[key];
var currentOptionTemplate = optionTemplate;
currentOptionTemplate = currentOptionTemplate.replace("{0}", key);
currentOptionTemplate = currentOptionTemplate.replace("{1}", value);
$("#selectedStream").append($(currentOptionTemplate));
}
});
Is that array necessary? If you're just trying to display the keys within that object I'd create a for loop:
var resp = { "streams": {"sweet": "cookies", "savory": "pizza"} }
for (property in resp.streams) {
$('#selectStream').append($('<option/>', {text: property, value: property}));
}
JSFiddle: http://jsfiddle.net/pWFNb/
Is it possible to create a property based on string values.
I have a Json object, which used to fill the UI (select box).
"Conf" :{
"Color":[
{
"Value":"BLUE"
},
{
"Value":"GOLD"
}
],
"Size":[
{
"Value":"12"
},
{
"Value":"11"
}
],
}
Based on the selection, I need to add it to an object (Item.Conf below).
addSel provides the selection type (Color, Size etc), and the value (BLUE, 11 etc).
How can I add the selection as shown below.
So if the choice is Color : BLUE, I need to add it as Item.Conf[0].Color.Value = "BLUE"
Is it possible?
Item = {
Conf: [],
addSel: function(type, val){ //for example type="Size", val = "11"
//.... need to selection to Conf
// add a member "Size" from type string
//set its value as val
console.log(Conf[0].Size.Value) //=> 11
}
}
In essence is it possible to make an object like
"Size":{
"Value": 11
}
from strings
Your question is not entirely clear for what exactly you're trying to do, but perhaps you just need to know about using the [variable] syntax to address a property name using a string.
Example:
var x = {};
var propName = "Value";
x[propName] = 11;
This is equivalent to:
var x = {};
x.Value = 11;
But, the first form allows the property name to be a string in a variable that is not known at the time you write the code whereas the second form can only be used when the property name is known ahead of time.
I want to get the ID values of multiple selection list. The multiple selection list
is generated dynamically. How to get that values? If i can able to get the values means,
can I convert it to JSON object or, it ll be obtained as JSON object!!!!
Here is my code to generate it dynamically.
function displayMultipleList() {
EmployeeManagement.getResponseList(function (respList) {
var respOptionsSelect = document.getElementById('respOptions');
var searchOptions = null;
for (var i = 0; i < respList.length; i++) {
var resp = respList[i];
selectOptions = document.createElement('option');
selectOptions.value = resp.respID;
selectOptions.innerHTML = resp.respName;
respOptionsSelect.appendChild(selectOptions);
}
});
}
Thanks.
You can use the serializeArray() function:
$("#respOptions").serializeArray()
It will return to you the selected objects in a JavaScript array which can be easily stringified to a JSON string.
If your <select> element looks like this (don't forget the name attribute, as serializeArray needs it!):
<select name="respOptions" id="respOptions" multiple="true">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
If items 2 and 3 were selected, you would get this back from the function:
[{ name: "respOptions", value: "2"}, {name: "respOptions", value: "3"}]
EDIT - I forgot to add the name attribute to the <select> element. Sorry for the confusion.
Taking the ambiguity of the question as a challenge, here are two options.
You're asking "how to get the values" and "convert it to JSON object." Taking that literally, and ignoring the mention of id, you can simply do this:
var x = JSON.stringify( $('#respOptions').val() );
...which will give you a simple (JSON) array of the selected values:
["somevalue","anothervalue"]
But if by "get the ID values" you mean "get the IDs and values of selected options", then you can do something like this:
var y = $('#respOptions option:selected').map( function(i,el){
var result = {};
result[ el.id ] = $(el).val();
return result;
}).get();
y = JSON.stringify(y);
...which will give you an array like this:
[{"id1":"somevalue"},{"id5":"anothervalue"}]
I threw together a fiddle that makes assumptions about your HTML, and mocks in the respList from which the options are dynamically added. It solves the problem both ways.
If your browser doesn't support JSON.stringify, you can use Crockford's oft-recommended json2.js library.
Here's how you iterate over a list of options inside a select element and get the ids:
http://jsfiddle.net/bXUhv/
In short:
$('option', $('#optionlist')).each(function() {
alert($(this).attr('id'));
});
With regard to converting any data into a JSON object, please look into this jQuery library.
Multiple select and If you want the id in a array format
fiddle Example here
var countries = [];
$.each($(".country option:selected"), function() {
countries.push($(this).attr("id"));
});
alert(countries.join(", "));