JSON jQuery no errors how to investigate - javascript

I don't see any error from console window, either I don't see that my code acted. How do I investigate and make my script fired correctly? Thanks
var mylist = [
{ title: 'a' },
{ title: 'b' },
{ title: 'c' },
{ title: 'd' },
{ title: 'e' },
{ title: 'f' },
{ title: 'g' },
{ title: 'h' },
{ title: 'i' },
{ title: 'j' },
{ title: 'k' },
{ title: 'l' },
{ title: 'm' },
{ title: 'n' },
{ title: 'o' },
{ title: 'p' },
{ title: 'q' }
];
$.getJSON(mylist, function( data ) {
var items = [];
console.log(items);
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-list",
html: items.join( "" )
}).appendTo( "body" );
});

You have a misunderstanding of what $.getJSON does. As you can read the in the documentation, the first argument must be a URL. $.getJSON then performs an Ajax request to the URL and parses the response as JSON.
You don't pass a URL and you don't even have JSON. All you have to do is iterate over the array:
var items = [];
$.each( mylist, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-list",
html: items.join( "" )
}).appendTo( "body" );
DEMO
I don't know which output you want, but that should give you a start. Read the $.each documentation, and learn about how to access objects.

Related

Need Some help to refactor or optimize the code in javascript object

I have tried writing the array of objects using ternary but still I am thinking to refactor the common properties between them if someone could help me with this would be helpful.
const{address } = A
data: conditionalValue ? [
{ text: text },
{ building: address },
{ ' ': pincode }
]:
[
{ text: text },
{ building: address },
{ ' ': pincode },
{ 'somevalue': someValue1 },
{ ' ': otherValue},
],
still the { text: text },{ building: address },{ ' ': pincode } objects are same between 2 condition
You can use some destructuring on a array of additional values:
const conditionalValue = false;
const data = [
{ text: 'text' },
{ building: 'address' },
{ ' ': 'pincode' },
...(
conditionalValue
? [{ 'somevalue': 'someValue1' },{ ' ': 'otherValue'}]
: []
)
];
console.log(data);
However, I think it might be cleaner to just push your other values into the data array.

How to pass multiple parameters in columns.render function in Datatables jquery?

I have data below and I want to pass two variables (id, name) in the columns.render function in Datatables.
What I have now is only pass the id in the render function.
I also want to pass name in the render function.
Thanks.
const myData = [
{ id: 2, name: "book" },
{ id: 5, name: "song" },
];
$("#example").DataTable({
data: myData,
columns: [
{
targets: 1,
data: "id",
render: function (data, type, row, meta) {
return (
"<button class='btn btn-default' data_id='" +
data + //id is passed to here
"'>" +
"name" + //the name I want to pass to here.
"</button>"
);
},
},
],
});
You can do it using the row parameter of render function.
const myData = [
{ id: 2, name: "book" },
{ id: 5, name: "song" },
];
$("#example").DataTable({
data: myData,
columns: [
{
targets: 1,
data: "id",
render: function (data, type, row, meta) {
return (
"<button class='btn btn-default' data_id='" +
data + //id is passed to here
"'>" +
row.name + //get the name using row parameter
"</button>"
);
},
},
],
});
More details about render function can be found at https://datatables.net/reference/option/columns.render

Jquery Autocomplete w/ Categories search, limited to Category chosen by user

The jquery Autocomplete demo page with category shows the following :
I want the user to choose the category (Products or People) in a separate button (dropdown list), and then the jquery search to return only the matches in the category chosen by user.
Expected result :
screenshot 2
I am new to jquery, but according to my research I think this could be possible using "functions" as inputs, as said in the answer here (even though the question was different) :
Jquery UI Autocomplete: search from multiple attributes of one array
However I don't know what to do next.
My current code is the code from official doc :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Categories</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<script>
$( function() {
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
},
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
var li;
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
li = that._renderItemData( ul, item );
if ( item.category ) {
li.attr( "aria-label", item.category + " : " + item.label );
}
});
}
});
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#search" ).catcomplete({
delay: 0,
source: data
});
} );
</script>
</head>
<body>
<label for="search">Search: </label>
<input id="search">
</body>
</html>
Using the example data, there was a bit more work to be done to setup the data to work better for this. If you have control over the data format, you can prepare it before hand to work better.
Working example: https://jsfiddle.net/Twisty/uy5f2fta/
HTML
<label>Search:</label>
<select id="categories">
<option value="none"></option>
</select>
<input id="search">
jQuery
var data = [{
label: "anders",
category: ""
}, {
label: "andreas",
category: ""
}, {
label: "antal",
category: ""
}, {
label: "annhhx10",
category: "Products"
}, {
label: "annk K12",
category: "Products"
}, {
label: "annttop C13",
category: "Products"
}, {
label: "anders andersson",
category: "People"
}, {
label: "andreas andersson",
category: "People"
}, {
label: "andreas johnson",
category: "People"
}];
$(function() {
// Set Variables
var cats = [],
labels = {},
sel = $("#categories"),
search = $("#search");
// Sift out specific Categories
$.each(data, function(k, v) {
if (v.category !== "") {
cats.push(v.category);
console.log("Found Cat: " + v.category);
}
});
$.unique(cats);
console.log("All Cats: ", cats);
// Set Categories into Select element
$.each(cats, function(k, v) {
sel.append("<option value='" + v + "'>" + v + "</option>");
});
// Create Object of various data
labels.none = [];
$.each(cats, function(k, v) {
labels[v] = [];
});
for (var i = 0; i < data.length; i++) {
$.each(cats, function(k, v) {
if (data[i].category == "") {
labels.none.push(data[i].label);
}
if (data[i].category == v) {
labels[v].push(data[i].label);
}
});
}
$.each(labels, function(k, v) {
$.unique(labels[k]);
});
console.log("All Labels: ", labels);
// Set Autocomplete with variable data based on category selection
search.autocomplete({
delay: 0,
source: function(req, res) {
var cat = sel.val();
var data = labels[cat];
var results = [];
$.each(data, function(k, v) {
if (v.indexOf(req.term) == 0) {
results.push(v);
}
});
res(results);
}
});
});
I first sifted out the categories that we knew would be in the data. This was then used to populate the Select element with a special "none" option. You could go back and adjust the none data to include all labels.
Next we parse all the labels and sort them into an object that has child arrays with the name of each category as the index. We will populate each array with the data for that category.
Finally, we use a function for the source so that we can pick which data set we want to read from. req.term is the data that was entered in the field, and we need to return an array of the matching data. The use of indexOf() is helpful here. This will return 0 when the term is at the beginning of the string. We then pass the resulting array to our res callback function.
So using your example, if category is "none" and we type "an", we get a resulting 'anders', 'andreas', and 'antal'. If we then type "and", the results drop to 'ansders' and 'andreas' as expected.

x-editable custom fields cannot get text of select menu

Ive followed this example from another SO thread:
X-editable custom field type not respecting overridden defaults
and its helped me to create a similar custom field with x-editable. All is working ok but i cant figure out how render/display the 'text' of the select - the SO example ouputs the 'value'. my js to initialis the x-editable to use my custom inputs is thus:
$('#stffulladdress').editable({
url : '',
pk : 6,
value : {
address : "",
city : "",
region : "",
postcode : "",
country : "eng"
},
sourceCountry: [
{ value: "eng", text: "ENGLAND" },
{ value: "ire", text: "IRELAND" },
{ value: "sco", text: "SCOTLAND" },
{ value: "cym", text: "WALES" }
],
validate : function(value) {
if (value.address == '' || value.postcode == '') return "Address first lines AND Postcode required";
},
display : function(value) {
if (!value) {
$(this).empty();
return;
}
console.log(value.country);
var html = $('<div>').html( value.address + '<br />' + value.city + '<br />' + value.region + '<br />' + value.postcode + '<br />' + value.country );
$(this).html(html);
}
});
My custom x-editable class is the same as the SO example mentioned with the only difference being i have more inputs -they work ok as expected. I would have thought that this snippet from the x-edit class gets the text of the selected item:
value2html: function(value, element) {
if(!value) {
$(element).empty();
return;
}
var countryText = value.country;
$.each(this.sourceCountryData, function (i, v) {
if (v.value == countryText) {
countryText = v.text.toUpperCase();
}
});
var html = $('<div>').html( value.address + ',<br />' + value.city + ',<br />' + value.region + ',<br />' + value.postcode + ',<br />' + countryText );
$(element).html(html);
},
But upn displaying the selected country i still get the country value "eng" and not the text "England".
I've tried :
value.country which gives me the value 'eng'
and value.text gives undefined
Any idea how i can get the selected text??
thanks
Try the sourceCountry as follow:
sourceCountry: [
{ "eng": "ENGLAND" },
{ "ire": "IRELAND" },
{ "sco": "SCOTLAND" },
{ "cym": "WALES" }
],

integrating facet match and value matches in visualsearch.js under a single function

Recently ive been searching for a good autocomplete plugin and I came across the visualsearch.js plugin. It really interested me. What I was wondering is instead of providing value matches for the facets that user selects, is it possible to get the value matches for the user input inside all the facet categories. Like if the user types in "AP", user should get matches to word "AP" inside all facets likes "access", "country".
To explain correctly, I want to take both facet and matched values programatically. not through a fixed set of input. Ive found a way to do one is this way
http://jsfiddle.net/HRuAP/49/
so if we select job.name inside job facet, it should select the facet name as job : job.name instead of getting the displaying it as job.name: and again going for some value matches. im trying to integrate value matches and facet matches in to a single function so both takes place on single click.
My input to visual search callback is in JSONJ format. {"Regions":[{"name":"africa"}],"Company":[{"name":"google"}],"Persons":[{"name":"marc zuckerberg"},{"name":"matt romney"}]}
is it possible to achieve it using visual search?
You can try this , i had the same situation too.
Try mixing two plugins.
one was jquery auto complete and the other is http://ioncache.github.com/Tag-Handler/ to create tags
First I integrated to "Categories" and "multi values" script in to one and added facet categorywise division in auto complete..
then added http://ioncache.github.com/Tag-Handler/ so that tags are created on entering or on selection
This is the script part
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$(document).ready(function(){
$(".methodButton").button();
$("#callback_tag_handler").tagHandler({
autocomplete: false,
onAdd: function(tag) { console.log('Added tag: ' + tag); return 1; },
onDelete: function(tag) { console.log('Deleted tag: ' + tag); return 1; }
});
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( ".tagInputField" )
// don't navigate away from the field on tab when selecting an item
.live( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
}).catcomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
data, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
if(ui.item.category=" "){
terms.push("Text : "+ ui.item.value );
}else{
terms.push(ui.item.category+" : "+ ui.item.value );
}
// add placeholder to get the comma-and-space at the end
//addTag();
terms.push( "" );
this.value = terms.join( " " );
return false;
}
});
});
and HTML part is
<div id="container">
<ul id="callback_tag_handler"></ul>
</div>
Thanks
Vineeth

Categories

Resources