How to get the id value of a multiple SELECTION using javaScript? - 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(", "));

Related

Unable to get string array in jquery

I am creating a array which contains text of selected values of a multi select bootstrap chosen-select.
But i am not getting desired output like:
["Navy", "Dark Blue", "Light Green"]
What I am getting is:
["NavyDark BlueLight Green"].
What is the reason..
This is my code..
$('[name="ci_claimed_for"]').each(function() {
names.push($('[name="ci_claimed_for"]').find("option:selected").text());
});
You don't even need to create a new array and then push into it: just use jQuery's .map() function:
var names = $('[name="ci_claimed_for"]').map(function() {
return $(this).find("option:selected").text());
}).get();
Remember to chain .get() in the end, because it will return a jQuery collection. Use .get() to reference the actual array returned.
Here is a proof-of-concept example:
$(function() {
var names = $('[name="ci_claimed_for"]').map(function() {
return $(this).find("option:selected").text();
}).get();
console.log(names);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ci_claimed_for">
<option value="John" selected>John</option>
<option value="Doe">Doe</option>
</select>
<select name="ci_claimed_for">
<option value="Jane" selected>Jane</option>
<option value="Doe">Doe</option>
</select>
You can do it in this
//take a empty arr
var names = [""];
$('[name="ci_claimed_for"]').each(function() {
$('[name="ci_claimed_for"] option:selected').each(function(){
names.push($(this).text());
});
});
then just shift your array:
names.shift();
You should be iterating it as follows:
CODE
var arr=[];
var data=$('[name="ci_claimed_for"]').find("option:selected")
for(var i=0;i<data.length;i++){
arr.push(data.eq(i).text())
}
console.log(arr) //desired result
Using the $('[name="ci_claimed_for"]').text() will return all the text in array of nodes obtained
For your js code .you need a $(this) inside the each .You iterate the each element but not pushing with each element to array
$('[name="ci_claimed_for"]').each(function() {
name.push($(this).val())
});
OR
$('[name="ci_claimed_for"]').each(function() {
names.push($(this).find("option:selected").text());
});

Associative Array in Javascript Key is number, but access as string (Associative)

I'm attempting to create a lookup table in Javascript that is populated ahead of time by a table (basically just turning a table into a Javascript array), then, a dropdown value is referenced for the "score" column of the table.
var pointsGrid=[];
// First column is the primary key in a table with the same layou
// Second column is the name of the move
// Third column is the score
pointsGrid.push(['1',"Run",0.1]);
pointsGrid.push(['2',"Jump",0.5]);
pointsGrid.push(['3',"Twist",0.9]);
<select id="moveSelect">
<option value="1">Run</option>
<option value="2">Jump</option>
<option value="3">Twist</option>
</select>
My question is during the onChange event, when I read the value of the dropdown, how do I reference the array by string, instead of by number?
For example:
pointsGrid["1"] not pointsGrid[1], like in pointsGrid["StringKey"]? It keeps going back to pointsGrid[1] which is pulling the wrong score value.
Thank you in advance,
Dan Chase
Arrays number-indexed data structures. Use objects instead.
var pointsGridObj = {}
pointsGridObj["1"] = ["Run", "0.1"]
pointsGridObj["2"] = ["Jump", "0.5"]
pointsGridObj["3"] = ["Twist", "0.9"]
Or if you have the triples as an array,
pointsGridobj = {};
for(var i=0; i<pointsGrid.length; i++) {
pointsGridobj[pointsGrid[i][0]] = pointsGrid.slice(1,3);
}

ng-repeats, showing record while it's value is a part of field of another object

I've got objects 'ing' with a field named 'id' and another one called 'fObj' with a field named 'contain'.
By using ng-repeat i'd like to show only these 'ing' objects where ing.id is a part of fObj.contain
e.g.
ing=[{id: 1,field: value},{id:2, field: othervalue},{id:3, field: cat}];
fObj={field1: value1, field: value2, contain: ':1:3:'};
By having this contain value I'd like to show only ing's with id=1 and id=3
Yeah, I know there are two types of data (number and string) but even if i changed numbers to strings it still didn't work
I just dont't know how to make it works. It's probably some kind of custom filter, but I've tried couples and nothing happend.
I would be glad if you suggest me a solution.
Thanks
In your controller,
var ids = fObj.contain.split(':');
// the array for your ng-repeat
var displayIng = [];
// loop the objects, see if the id exists in the list of id's
// retrieved from the split
for(i = 0; i < ing.length; i++) {
if(ids.indexOf(ing.id.toString()) displayIng.push(ing[i]);
}
I would split the numbers out of fObj.contain; and use them as hashmap object keys for simple filtering of the array
var ing=[{id: 1},{id:2},{id:3}];
var fObj={contain: ':1:3:'};
var IDs = fObj.contain.split(':').reduce(function(a,c){
a[c]=true;
return a;
},{});
// produces {1:true,3:true}
var filtered = ing.filter(function(item){
return IDs[item.id];
});
console.log(filtered)

Creating Select Box from options stored in a variable

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/

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]

Categories

Resources