I have a json string that I wish to add to select2 multiselect search input. I am getting map error as below
Cannot read property 'map' of undefined
The json field from console log is
[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]
And the js code is
var employees = $(this).attr('data-employees');
console.log(employees);
$("select[name='employees[]']").val(employees.data.map(function(x) {
return x.id; })); // Set the selected data before show it.
$('select').select2()
HTML
<select multiple="multiple" name="employees[]" id="form-field-select-4" width="200px "class="form-control search-select"></select>
As I can see you are getting this array from element attribute and if you are, probably the console.log is a string so, try this:
var employees = JSON.parse( $(this).attr('data-employees') );
console.log(employees);
$('select').select2(); // init with select2
$("select[name='employees[]']").val(employees.map(function(x) {
return x.id; // Set the selected data before show it.
}))
.trigger("change");
If you see this
var employees = JSON.parse('[{"id":1,"name":"Test Test"},{"id":2,"name":"Billy A"}]');
console.log('The whole array:', employees); // you have a valid array
var ids = employees.map(function(x){ return x.id; })
console.log('Employee ids only: ', ids);
Edited
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 am trying to load some usernames returned via ajax into a dropdown menu using jQuery. The results are successfully getting into the dropdown menu but all the data is getting into just one option tag. I want the data to be in different option tags.
Currently the dropdown menu looks like this
Name1,Name2,Name3,Name4
But I want as:
Name1
Name2
Name3
Name4
Dropdown where I am putting the results:
<div class="form-group">
<select name="name" class="form-control" id="employee_select">
</select>
</div>
jQuery:
//send value via GET to URL
var get_request = $.ajax({
type: 'GET',
url: '/users',
data: {User:User}
});
// handle response
get_request.done(function(data){
// Data returned
dataReturned = data;
// Log data
console.log($.type(dataReturned)); // response is string in the form of
// Name1
// Name2
// Convert to an array
dataArray = [dataReturned]
// Create a new array
newArray = [];
// Populate newArray with items
for(i=0;i<dataArray.length;i++){
if(typeof(dataArray[i])=='string'){
newArray.push(dataArray[i])
}
}
//console.log(newArray);
console.log($.type(newArray)); // an array is returned in the form of ["Name1,Name2,Name3,Name4"]
// Loop through newArray
$.each(newArray, function( index, value) {
$('#employee_select').append("<option>"+ value + "</option>");
})
Thank you.
There's probably a more elegant way of doing this but...
What if you pushed each result into an array and then ran a for loop through each item in array checking to see if each item is a string. The successful results of that, you push into a final array.
for(i=0;i<array.length;i++){
if(typeof(array[i])=='string'){
newArray.push(array[i])
}
}
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/
I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array
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');