Creating Select Box from options stored in a variable - javascript

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/

Related

Passing Hash Table/Dictionary with a loop in JavaScript

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...

How to fetch existing JSON that exists in data-attr and update that

In the given fiddle , click on Addons buttons and on selection and unselection
of Checkboxes , i am trying to update the data-attr
array present as data-stuff .
Once i set the data how can i fetch the existing and update it with new data .
http://jsfiddle.net/kgm9o693/9/
// checkbox checked
$(document).on('click', '.ui-checkbox-off', function (event) {
var vendoritemsdata = $(".lastItm_Wrap").data('stuff');
var checkboxid = $(this).next().attr("id");
var cost = $(this).attr("cost");
var toppcrusts = [];
toppcrusts.push({
'name': checkboxid,
'cost': cost
});
if (vendoritemsdata.length == 0) {
$('.lastItm_Wrap').attr('data-stuff', toppcrusts);
}
else {
var existingdata = $('.lastItm_Wrap').data('data-stuff');
}
});
Could you please tell me how to resolve this ??
You are trying to use the DOM as a variable. It should be the other way around. Use the DOM only to show results (total cost in your case). But before that keep everything into an array serialize the array if you need it as json or data-stuff.
Examine the example at the bottom of this http://api.jquery.com/serializeArray/
If you want to keep doing it your way, convert the data to JSON and use this:
Set data
$('.lastItm_Wrap').attr('data-stuff', JSON.stringify(toppcrusts) );
Get data
var existingdata = JSON.parse( $('.lastItm_Wrap').attr('data-stuff') );
http://jsfiddle.net/kgm9o693/12/

Variable text label for select dropdown in jquery

I have a function that, taking a JSON array of objects, where each object has an id and a text field label (variable for each select), it populates the options.
The function I am trying to write is:
function populateSelect(urlString, id, tag){
$.getJSON(urlString, function(data){
$.each(data, function(){
$(id).append($("<option></option>").text(this.tag).val(this.id));
});
});
}
So this.id will always be true as every JSON obect will have an attribute where the key is 'id'. Yet this.tag is what I want to be variable as this can change for each type of JSON object/select I am building.
For example, two valid JSON objects I could be working with are:
[{id:'1', name:'John Doe'}, {id:2, name:'Jane Doe'}]
and
[{id:1, model:'Toyota'}, {id:2, model:'Honda'}]
Each of these JSON objects would be used to populate the <option> fields for the respective <select> element. Thus for the first JSON object if this was not a function to be used for many different Select elements, that line would read:
$.(id).append($("<option></option>").text(this.name).val(this.id));
and the second JSON object would have a line that read:
$.(id).append($("<option></option>").text(this.model).val(this.id));
Apologies if any of the jargon is incorrect, I'm coming up to speed with JQuery.
I think what you are looking for is this:
$.each( data, function( key, value ) {
//get all the properties of the object
var keys = Object.keys(value);
var option = document.createElement('option');
option.value = value.id;
//use the second property as inner html
option.innerHTML = value[keys[1]];
$("#mySelect").append(option);
});
http://jsfiddle.net/e55kW/1/
I updated the jsFiddle of #jmm
#Yoeri pointed out your typo with $.()
Is this fiddle what your trying to attempt?
I just created a string and appended it to the select element.
$.each( data, function( key, value ) {
var option = "<option value="+value.id +">"+ value.name + "</option>";
$("#mySelect").append(option);
});
Found out (prior to coming back and seeing Yoeri's also correct response) that this works:
function populateSelect(urlString, id, tag){
$.getJSON(urlString, function(data){
$.each(data, function(){
$(id).append($("<option></option>").text(this[tag]).val(this.id));
});
});
}
The difference from the above is that I changed this.tag to this[tag]

Dojo: option[selected ='selected'] not working for run-time change

I am working on a multi-select box and found
var count = dojo.query("option[selected ='selected']", dojo.byId('select_id')).length;
Always returns whatever original from the page(database) but yet what user selected at run-time. I am running on Dojo 1.6. So how can I count number of selected options from multi-select box AT RUN-TIME?
I made a page that shows users and the groups they are in. Here is some of the code. I had to rip some stuff out to make it concise. The last line of code answers the question. It returns an array with the checked values.
// Programattically create the select.
var _groups = new dojox.form.CheckedMultiSelect({
multiple : true,
class : "cssThing"
}, "groups" + _userNumber);
// Fill the CheckedMultiSelect boxes with unchecked data.
var tempArray = new Array();
dojo.forEach(groupList, function(row, index) {
tempArray.push({
value : row.value,
label : row.label,
selected : false,
});
});
_groups.addOption(tempArray);
// Populate the CheckedMultiSelect with an array.
var tempArray = [];
dojo.forEach(user.groups, function(row) {
tempArray.push(String(row.groupName));
});
_groups.set('value', tempArray);
// Get the CheckedMultiSelect values as an array.
_groups.get('value');

How to get the id value of a multiple SELECTION using javaScript?

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(", "));

Categories

Resources