array sort alphabetic order into dropdown javascript - javascript

I have a empty dropdown list and a array however i want to display my array in my dropdown list in alphabetic order. How can i achieve this ?
<select id="dropdown">
</select>
var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];

var array = ["vintage","frames","treats","engraved", "stickers", "jewelerybox", "flask"];
array.sort(function(val1 , val2){
return val1.localeCompare(val2);
});
console.log(array); // ["engraved", "flask", "frames", "jewelerybox", "stickers", "treats", "vintage"]

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);
}

2 dimensional array lookup intersect in Javascript

I want to write a code which will obtain the intersection value of a row and column of an array.
I've a table below which is a slab for calculating incentive of employees.
When user puts achievements percent and sales value the result should be the intersection value of the respective column and row.
Example: When user puts 106-110 & 42000 in editText fields the result would come out 14919.
I did it in excel by Vlookup & Match function but I'm helpless here. I'm unable to figure out which formula would work here.
Not sure if you need a search here at all. You may have it already built-in into the data (seems static enough).
If your array is defined like this:
var arr = {
"60000": {
"100": "2,625",
"101-105": "7,500"
....
},
"120000":{
"100": "2,888",
"101-105": "8,250"
.....
}
....
}
Then
arr["120000"]["100"]
"2,888"
But... why is it android?
You can structure your data this way:
var array = [
[ 2625, 2888 ... ], // index 0 ->100
[ 7500, 8250 ...], // index 1 ->101-115
];
Enter the combination:
<select id="val1">
<option value="0">100</option>
<option value="1">101-105</option>
....
</select>
<select id="val2">
<option value="0">60000</option>
<option value="1">12000</option>
</select>
And than return the mapped value:
//... code to get val1 and val2
function getReward(row,col){
return array[row][col];
}

How can I filter a string array in ng-repeat with another string array?

I have a select element that I want to filter:
<select multiple="multiple" class="span2" data-ng-model="selectedParameters">
<option data-ng-repeat="parameter in availableParameters">
{{parameter}}
</option>
</select>
"availableParameters" is a string array that I can reach from here without problem, and "selectedParameters" is another string array that represents the selected elements in the UI.
availableParameters = ["AAA", "BBB", "CCC", "DDD"];
I have another string array under object graph (accessible inside the HTML)
graph.parameters = ["AAA", "BBB"];
I am trying to filter "availableParameters" by "graph.parameters" and obtain a list like this: "CCC", "DDD"
I checked AngularJS's documentation but couldn't see an example for my problem.
All I could do is something like this:
<option data-ng-repeat="parameter in availableParameters | filter: !graph.parameters ">{{parameter}}</option>
You can make a custom filter to filter out all of the items that aren't in graph.parameters:
angular.module('yourModuleNameHere').filter('params', [function(){
return function (items, filterBy) {
return items.filter(function(currentItem){
return filterBy.indexOf(currentItem) === -1;
});
};
}]);
Afterwards you can use it as:
<select multiple="multiple" class="span2" data-ng-model="selectedParameters">
<option data-ng-repeat="parameter in availableParameters | params:graph.parameters">
{{parameter}}
</option>
</select>
You can do it in many ways, a filter is useful when the data can change but I think that isn't your case, you just need to add a simple business login in your controller... have a look on what follows:
var rawlist = ['foo', 'baz', 'bar'];
var blacklist = ['baz'];
var list = rawlist.filter(function(item) {
return blacklist.indexOf(item) < 0;
});
console.log('available parameters are', list);
so, your view can be:
<select ng-model="someScopeProperty" ng-options="item for item in list track by $index"></select>

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