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());
});
Related
https://api.myjson.com/bins/7xq2x this is my JSON data I want to display the keys in dropdown. My JSON data will be dynamic so I want code for dynamic JSON data to take only the keys
function renderBusinessUnitChart(){
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
Keys: name, abbreviation - this should display in dropdown.
For displaying keys:
function renderBusinessUnitChart(){
var ddown = document.querySelector('#dropdown') // I don't know what kind of dropdown do you have, so we will use regular select
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
const itemKeys = Object.keys(result[0]) // getting keys from first item of result array
var options = itemKeys.map(key => { // looping the keys
const option = new Option(
key,
key
) // creating a one option item for dropdown
ddown.appendChild(option) // adding option to dropdown
return option // returning option and adding it to array
})
console.log (options) // aray of options you will need it for some reason
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
For displaying keys where objects can contain different keys:
function renderBusinessUnitChart(){
// I don't know what kind of dropdown do you have, so we will use regular select
var ddown = document.querySelector('#dropdown')
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result) {
result = [ // for testng purposes only, to check that result may contain objects with different keys
{"name":"Alberta","abbreviation":"AB"},
{"name2":"British Columbia","abbreviation2":"BC"}
]
const options = result // getting array of unique keys from every item in result
.reduce((ac, item) => [...ac, ...Object.keys(item).filter(key => !~ac.indexOf(key))], [])
.map(key => { // looping the keys
// creating a one option item for dropdown
const option = new Option(key, key)
// adding option to dropdown
ddown.appendChild(option)
// returning option and adding it to array
return option
})
// aray of options you will need it for some reason
console.log (options)
}
})
}
$(document).ready(function(){
renderBusinessUnitChart()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
For displaying values:
function renderBusinessUnitChart(){
var ddown = document.querySelector('#dropdown') // I don't know what kind of dropdown do you have, so we will use regular select
$.ajax({
url: "https://api.myjson.com/bins/7xq2x",
success:function(result){
var options = result.map(_ => { // looping the result
const option = new Option(
_.name,
_.abbreviation
) // creating a one option item for dropdown
ddown.appendChild(option) // adding option to dropdown
return option // returning option and adding it to array
})
console.log (options) // aray of options you will need it for some reason
}
});
}
$(document).ready(function(){
renderBusinessUnitChart();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown"></select>
You can use Object.keys(inputObject) method to get an array of inputObject keys.
So in your case:
// Need to make sure your result is an object instead of array;
var resultObj = Array.isArray(result) ? result[0] : result;
function populateOptions(resultObj){
return Object.keys(resultObj).map(key => {
return `<option value="${key}">${key}</option>`
}).join("");
}
var selectHtml = `<select>${populateOptions(resultObj)}</select>`
See more:
Array.prototype.map()
Array.prototype.join()
Template literal (it's the (``) syntax)
Object.keys()
I want to fetch only 1st element of json array
my json data :
{
id:"1",
price:"130000.0",
user:55,
}
{
id:"2",
price:"140000.0",
user:55,
}
i want to access the price of 1st json element
price : "13000.0"
my code
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
});
but my output
is '1'
Assuming that you have array of objects
var arr = [{
id:"1",
price:"130000.0",
user:55,
},
{
id:"2",
price:"140000.0",
user:55,
}]
console.log(arr[0].price)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You data isn't valid JSON, JSON data key must be wrap within double quote, but your data isn't wrapped in double quote
var data = [{
"id":"1",
"price":"130000.0",
"user":55
},{
"id":"2",
"price":"140000.0",
"user":55
}]
console.log(data[0]["price"]);
Hello You just need to add [] from starting and ending point of your json string. see here var data = JSON.parse( '[{ "id":"1","price":"130000.0","user":55},{"id":"2","price":"140000.0","user":55}]');
var priceValue = 0;
$.each(data, function(index, element) {if(index == 0){ priceValue = element.price;}});console.log(priceValue);
Your answer will be 13000.0
The element having the your JSON data means, we can able to use below code to get the first JSON data.
element[0].price
Thanks,
You are using for each loop and in function you get 2 params first one is index and second is the element itself. So this will iterate through all elements.
$.each(data_obj, function(index, element) {
$('#price').append(element.price);
});
If you just want to get first element
$('#price').append(data_obj[0].price);
var my_first_json_obj = data_obj[0]; // Your first JSON obj (if it's an array of json object)
var my_price = my_first_json_obj.price; // Your price
$('#price').append(my_price);
If you want only the first item's price, you don't need a loop here.
$('#price').append(data_obj[0].price);
would work here.
For further reading you can refer here
Following is the solution worked for my problem
I use return false;
$.each(data_obj, function(index, element) {
$('#price').append(element.price[0]);
return false;
});
Which gives only 1st value of array elements.
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"]
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>
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(", "));