JSON Parser with jquery.TokenInput (format) - javascript

I have a problem with jquery.tokenInput.
This is my tokenInput code:
$(".search-betrocket").tokenInput("http://www.websitehere.com/web/search", {
searchDelay: 2000,
minChars: 3,
tokenLimit: 5,
hintText: "Buscador inteligente...",
noResultsText: "Sin resultados",
searchingText: "Buscando...",
theme: "facebook",
queryParam: "txt",
propertyToSearch: "NickName",
resultsFormatter: function(item){ return "<li>" + "<img src='" + Users.Avatar + "' title='" + item.first_name + " " + item.last_name + "' height='25px' width='25px' />" + "<div style='display: inline-block; padding-left: 10px;'><div class='full_name'>" + item.first_name + " " + item.last_name + "</div><div class='email'>" + item.email + "</div></div></li>" },
tokenFormatter: function(item) { return "<li><p>" + item.first_name + " <b style='color: red'>" + item.last_name + "</b></p></li>" }
});
The problem is de parser...
jquery not know much as to understand the json parser returned objects.
This is my code JSON result _GET request
{
Users: [
{
Id: 264,
NickName: "SirBet",
Avatar: "19b452bf3fe83e17de82b67e518361d2",
Ranking: 3233,
FirstName: "Sir",
LastName: "Bettor",
Gender: "H",
Location: "Valencia",
Description: "Acepto todo tipo de retos :)",
CountryId: 1,
Country: "España",
CountryISO: "ES",
PrivacyUpdated: 0
}
]
}
What is not is how to navigate the json object to function properly.
Ie enter via $val['Users']['0']['Nickname'] format but jquery / json.
Does anyone help me?

if ur json is...
[{Id:1, NickName:xxxx, Avatar: "19b452bf3fe83e17de82b67e518361d2", Ranking: 3233}]
then..
$.each(data, function(a, b) {
alert (b.Id);
alert (b.NickName);
alert (b.Avatar);
alert (b.Ranking);
});

Related

Knex how to build an array POSTGRES query

i try to query some data with knex.js using this:
let query = knex
.select(
'project.custom_answer.id',
'project.custom_answer.content',
'project.custom_answer.is_private',
knex.raw(
'CASE ' +
'WHEN proposal.custom_question.id IS NULL THEN NULL ' +
'ELSE json_build_object(' +
"'id', proposal.custom_question.id," +
"'content', proposal.custom_question.content," +
"'is_mandatory', proposal.custom_question.is_mandatory," +
"'is_private', proposal.custom_question.is_private," +
"'has_media', proposal.custom_question.has_media," +
"'category', proposal.custom_question.category," +
"'type', proposal.custom_question.type," +
"'proposal'," +
'CASE ' +
'WHEN proposal.proposal.id IS NULL THEN NULL ' +
'ELSE json_build_object(' +
"'id', proposal.proposal.id," +
"'is_private', proposal.proposal.is_private," +
"'slug', proposal.proposal.slug," +
"'name', proposal.proposal.name" +
')' +
'END' +
') ' +
'END as custom_question'
)
)
.select([
knex.raw(
'CASE ' +
'WHEN proposal.custom_answer.id IS NULL THEN NULL ' +
'ELSE ARRAY_AGG(json_build_object(' +
"'id', proposal.custom_answer.id," +
"'content', proposal.custom_answer.content" +
'))' +
'END as custom_answer'
),
])
.modify(querybuildUtils.mediaBuilder, 'project.custom_answer.media_id')
.join(
'proposal.custom_question',
'proposal.custom_question.id',
'project.custom_answer.custom_question_id'
)
.leftJoin(
'proposal.custom_answer',
'proposal.custom_answer.custom_question_id',
'proposal.custom_question.id'
)
.join('proposal.proposal', 'proposal.proposal.id', 'proposal.custom_question.proposal_id')
// .modify(joinUserAsObject,"project.answer.member_id")
.from('project.custom_answer')
.limit(100)
.whereIn('project.custom_answer.id', arrayId)
// .where("project.custom_answer.is_private", "false")
.orderBy('project.custom_answer.created_at', 'desc')
.groupBy(
'project.custom_answer.id',
'proposal.custom_question.id',
'proposal.custom_answer.id',
'proposal.proposal.id'
);
I want to get my custom_question with the first knex.raw and create an array for my custom_answer with the second knex.raw.
My issue here is that create an array for each custom_question AND custom_answer so now my data look like:
custom_answers: [
{
content: "",
custom_answer: [{id: 59, content: "A1"}]
custom_question: {id: 236, content: "Q1" ....}
...
},
{
content: "",
custom_answer: [{id: 60, content: "A2"}]
custom_question: {id: 236, content: "Q1" ....}
...
},
]
And that what i want:
custom_answers: [
{
content: "",
custom_answer: [
{id: 59, content: "A1"},
{id: 60, content: "A2"},
]
custom_question: {id: 236, content: "Q1" ....}
...
}
]

JQuery hide/slideToggle elem in scope

I'm new to jQuery and looking for a solution, how to add a list of ul id = "animalsListDetails", hide / show on the HTML page and rendering this scope, when click a-ref:
function renderAnimalsList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#animalsList li').hide();
$('#animalsListDetails li').hide();
$.each(list, function (index, animals){
$('.animals').click(function () {
$(this).next().slideToggle();
}).append('<ul id="animalsList"><li> Animal Id: ' + animals.id + '<br> <ul id="animalsListDetails"><li> Name: '+ animals.animalname + '<br> Birthday: ' + animals.dateborn + '<br> Sex: ' + animals.sex + '<br> Type animal: ' + animals.typesanimalsId + '</li></ul></li></ul>');
});
}
call function:
function findAnimalByCustomerId(customerId){
console.log('findAnimalByCustomerId: ' + customerId);
$.ajax({
type: 'GET',
url: customerlistURL + '/' + customerId + '/myanimals',
dataType: "json",
success: function (data) {
console.log('findAnimalByCustomerId success: ' + customerId);
renderAnimalsList(data);
}
});
}
HTML:
<div class="animals">
</div>
If the main motive of question is to know how to add the list, following answer shows that with mocked data. If you wanna know more, please ask in comments (try to define your problem at once).
function renderAnimalsList(data) {
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#animalsList li').hide();
$('#animalsListDetails li').hide();
$.each(list, function(index, animals) {
$('.animals').click(function() {
console.log(this);
$(this).next().slideToggle();
}).append('<ul id="animalsList"><li> Animal Id: ' + animals.id + '</li>');
//whith details
$('#animalsList').append('<ul id="animalsListDetails"><li>Name: ' + animals.animalname + '<br> Birthday: ' + animals.dateborn + '<br> Sex: ' + animals.sex + '<br> Type animal: ' + animals.typesanimalsId + '</li></ul>');
});
}
var animals = [{
animalname: 'Tiger',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 10
}, {
animalname: 'Tiger 2',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 11
}, {
animalname: 'Tiger 3',
dateborn: '----.--.--',
sex: 'M',
typesanimalsId: 1,
id: 12
}]
function findAnimalByCustomerId(customerId) {
// This function is useless in this context
console.log('findAnimalByCustomerId: ' + customerId);
$.ajax({
type: 'GET',
url: customerlistURL + '/' + customerId + '/myanimals',
dataType: "json",
success: function(data) {
console.log('findAnimalByCustomerId success: ' + customerId);
renderAnimalsList(data);
}
});
}
//This ready function will be calling renderAnimalsList in same way as it will be called in above findAnimalByCustomerId
$(document).ready(function() {
renderAnimalsList(animals);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="animals">
<div id="animalsList"></div>
<div id="animalsListDetails"></div>
</div>
Here is solution:
(function($, undefined){
$(function(){
$(document).ready(function(){
//bind handlers
function domHandlers() {
$('.animal-id').click(function(e){
slideToggle(e);
});
}
function renderAnimalsList(jsonData) {
var list = jsonData;
$.each(list, function (i, animal) {
$('#animalsList').append('<li> Animal Id: ' + animal.id + '</li>');
//With details:
$('#animalsList').append('<li class="animal-details hidden">' +
'Name: ' + animal.animalname + '<br>' +
'Birthday: ' + animal.dateborn + '<br>' +
' Sex: ' + animal.sex + '<br>' +
' Type animal: ' + animal.typesanimalsId + '</li>');
});
}
function slideToggle(e) {
$('.animal-details ').addClass('hidden');
$(e.target).closest('li').next().removeClass('hidden');
}
renderAnimalsList(jsonData);
domHandlers();
});
});
})

Twitter Typeahead returning full object on result

I'm having a problem with twitter typeahead along with C# MVC, when it's autocomplete, it prints the entire object to my input:
My code:
var states = [];
#foreach (var item in ViewBag.Clubes)
{
#:states.push({ "Nome" : "#item.Nome", "Id" : "#item.Id" })
}
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1,
valueKey: 'Nome',
displayKey: 'Nome'
},
{
name: 'value',
source: substringMatcher(states),
templates: {
empty: [
'<div class="empty-message">',
' Clube não encontrado ',
'</div>'
].join('\n'),
suggestion: function (data) {
return "<strong>" + data.Nome + " " + data.Id + "</strong>";
}
}
});
The values on the drop-down suggestion works fine, but when I select them he fills the input with the array object, anyone knows how can I solve it?
Thanks.
Simply set a value to your typeahead input box as follows
$('.typeahead').typeahead('val',data.Nome);
Here is your final code
var states = [];
#foreach (var item in ViewBag.Clubes)
{
#:states.push({ "Nome" : "#item.Nome", "Id" : "#item.Id" })
}
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1,
valueKey: 'Nome',
displayKey: 'Nome'
},
{
name: 'value',
source: substringMatcher(states),
templates: {
empty: [
'<div class="empty-message">',
' Clube não encontrado ',
'</div>'
].join('\n'),
suggestion: function (data) {
return "<strong>" + data.Nome + " " + data.Id + "</strong>";
}
}
}).on('typeahead:selected', function(e, data) {
$('.typeahead').typeahead('val',data.Nome);
});

jQuery Datatable make each cell a link

I have four entities, let's say A,B,C,D which are interconnected (B depends on A, C depends on B, D depends on C). I want to display all the information in one table that can be easily searched and filtered.
So I created a view model of form:
public class MyViewModel {
public Aname {get; set;}
public Alink {get; set;}
public Bname {get; set;}
public Blink {get; set;}
public Cname {get; set;}
public Dname {get; set;}
public Dlink {get; set;}
}
I want the table to have four columns to display the name of each entity and each data in a cell to be a hyperlink that leads to the details page of the selected entity (except entity C).
Here is the javascript
$('#myDataTable').DataTable({
'bDestroy': true,
"bInfo": true,
"bProcessing": true,
"bDeferRender": true,
'iDisplayLength': 10,
'sPaginationType': 'full_numbers',
'sPageButtonActive': "paginate_active",
'sPageButtonStaticDisabled': "paginate_button",
'data': OptionsHandler.Data,
"columnDefs": [
{
"render": function (data, type, row) {
return "<a href=" + row[1] + "'>" + row[0] + "</a>";
},
},
]
});
But it complains that
Requested unknown parameter 0 for row 0. For more information about
this error, please see http://datatables.net/tn/4
Data is in Json format:
data = [
{"Aname":"PatriceBoyle",
"Alink":"/A/Details/00014",
"Bname":"Software Engineering",
"Blink":"/B/Details/2",
"Cname":"info",
"Dname":"Database Design",
"Dlink":"/D/Details/1"
}, etc.]
How can I say: return "<a href=" + link + "'>" + name + "</a>"; for each cell?
row[1] implies either an array index or object property name of '1' but you have neither.
You need something like:
return "<a href=" + row.Alink + "'>" + row.Aname + "</a>";
I stripped your code down to the minimum and got the same error until I changed you columndefs to columns instead:
columns: [
{ title: "Aname", data: "Aname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[0] + "</a>"; } },
{ title: "Alink", data: "Alink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[1] + "</a>"; } },
{ title: "Bname", data: "Bname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[2] + "</a>"; } },
{ title: "Blink", data: "Blink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[3] + "</a>"; } },
{ title: "Cname", data: "Cname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[4] + "</a>"; } },
{ title: "Dname", data: "Dname", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[5] + "</a>"; } },
{ title: "Dlink", data: "Dlink", render: function (data, type, row) { return "<a href=" + row[1] + "'>" + row[6] + "</a>"; } }
]
I managed to do it combining the two answers:
columns: [
{ title: "Column A", data: "Aname", render: function (data, type, row) { return "<a href=" + row.Alink + "'>" + row.Aname + "</a>"; } },
{ title: "Column B", data: "Bname", render: function (data, type, row) { return "<a href=" + row.Blink + "'>" + row.Bname + "</a>"; } },
{ title: "Column C", data: "Cname", render: function (data, type, row) { return "<a href=" + row.Clink + "'>" + row.Cname + "</a>"; } },
{ title: "Column D", data: "Dname", render: function (data, type, row) { return "<a href=" + row.Dlink + "'>" + row.Dname + "</a>"; } },
]

jQuery - output this list of objects in 3 columns

Can someone tell me how to output this list of objects in 3 columns and sort the list alphabetically? I tried else if but...
CSS:
.main {
float:left;
width:150px;
background:#9c9;
}
.center {
float:left;
width:150px;
background:#c9c;
}
HTML:
<head>
<script type="text/javascript">
var data = [
{name: "Dan", age: 25, desc: "test"},
{name: "Aary", age: 15, desc: "description"},
{name: "Bary", age: 15, desc: "description"},
{name: "Cary", age: 15, desc: "description"},
{name: "Dary", age: 15, desc: "description"},
{name: "Fary", age: 15, desc: "description"},
{name: "Tom", age: 18, desc: "haaha"}
];
function findName(personName){
return $.grep(data, function(item){
return item.name == personName;
});
}
function details(personName)
{
var person = findName(personName.toString())[0];
$('#description').html(person.desc);
}
</script>
</head>
<body>
<div>
<div class='main'>
</div>
<div class='center'>
</div>
<div id="description">
</div>
</div>
</body>
JS:
$(function () {
for (var i = 0; i < data.length; i++) {
if (i % 2 == 0) {
$('.main').append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>");
} else {
$('.center').append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>");
}
}
});
http://jsfiddle.net/KKYZj/8/
You just need to add another div column: <div class='right'></div>
And then change your javascript to:
$(function () {
data.sort(function (a, b) { return a.name > b.name; });
for (var i = 0; i < data.length; i++)
{
var target = [$('.main'), $('.center'), $('.right')][i % 3];
target.append("<a onclick='javascript:details(\"" + data[i].name + "\")'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a></br>");
}
});
Look here.
Ok. I put all data items in same containers with float: left; property. When need to break line and start new row of items we put <br style="clear: both"> element depending on condition if(i%3 == 0) where 3 is column count. Also I modified click handlers for elements.
js:
var data = [
{name: "Dan", age: 25, desc: "test"},
{name: "Aary", age: 15, desc: "description"},
{name: "Bary", age: 15, desc: "description"},
{name: "Cary", age: 15, desc: "description"},
{name: "Dary", age: 15, desc: "description"},
{name: "Fary", age: 15, desc: "description"},
{name: "Tom", age: 18, desc: "haaha"}
];
function findName(personName){
return $.grep(data, function(item){
return item.name == personName;
});
}
$(function() {
for(var i=1;i<data.length;i++)
{
var dataItem = "<a href='#' class='dataItem' data-description='" + data[i].desc + "'>" + data[i].name + " <strong>(" + data[i].age + ")</strong>" + "</a>";
$('.main').append(dataItem);
if(i%3 == 0) {
$('.main').append("</br>") ;
}
}
var description = $('#description');
$('a.dataItem').on('click', function(e){
description.text($(this).data('description'));
})
});
html:
<div>
<div class='main'>
</div>
<div id='description'></div>
</div>
css:
.main a{
display: block;
float:left;
width:150px;
background:#9c9;
}
Don`t need to put js code and html, body, head tags in html area

Categories