Easyautocomplete links AND images - javascript

I've been looking around and haven't been able to find an answer to this. I can get JQuery Easyautocomplete (http://easyautocomplete.com/) to work with Links, then get it to work with images, but I can't seem to get it to work with both. I'm new to JavaScript. I'm not sure what I'm doing wrong.
Here is my code...
var options = {
data: [
{
"text": "Home",
"website_link": "http://easyautocomplete.com/",
"icon": "http://lorempixel.com/100/50/transport/6"
},
{
"text": "Github",
"website_link": "https://github.com/pawelczak/EasyAutocomplete",
"icon": "http://lorempixel.com/100/50/transport/6"
}
],
getValue: "text",
template: {
type: "custom",
fields: {
website_link: "website_link"
},
method: function(value, item) {
return "<img src='" + item.icon + "' />" + value + "";
}
}
};
jQuery("#loan-officer-select").easyAutocomplete(options);
What am I doing wrong here? Any help would be greatly appreciated.

check if this is what you want
var options = {
data: [
{
"text": "Home",
"website_link": "http://easyautocomplete.com/",
"icon": "http://lorempixel.com/100/50/transport/6"
},
{
"text": "Github",
"website_link": "https://github.com/pawelczak/EasyAutocomplete",
"icon": "http://lorempixel.com/100/50/transport/6"
}
],
getValue: "text",
template: {
type: "custom",
method: function(value, item) {
return `<div>
<img src="${item.icon}" width="50px" height="50px" />
<a href=${item.website_link}> click me to go to ${value}</a>
</div>`;
}
}
};
jQuery("#loan-officer-select").easyAutocomplete(options);

Related

How can I give a different class for each header in a loop

I've been trying to make a HTML page where each box represents 1 item that has been ordered. Here's the HTML for the box:
<div id="boxMaster" class="small-box bg-info" class="box-PEDIDO" hidden>
<a class="nmroPedido small-box-header" id="header"></a> <a class="float-right" id="dataEntrega">28/09/2021
16:00</a>
<hr>
<div class="inner">
<p id="nomeproduto"></p>
</div>
<div class="icon">
<i class="fas fa-shopping-cart" id="carrinho"></i>
</div>
<hr id="footer" class="baixoHr">
<a href="#" class="small-box-footer"> Fruta > Tropical > Manga > Tommy   
</a>
</div>
And this is how I'm treating the data to feed it:
fetch('http://---.--.14.--:--/pedidos/', {
method: 'GET',
headers: {
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwiaWF------yNTkwLCJleHAiOjE2MzM3Nzg5OTB9.XwrGFhLiGJ0YS5FHjn7Xo',
'Content-type': 'application/json'
}
})
.then(function (response) {
return response.json();
})
.then(function (jsonResponse) {
// console.log(jsonResponse);
var DadosPedidos = jsonResponse;
pedidosArray = jsonResponse.length;
for (let pedidos of DadosPedidos) {
let a = 0;
for (let i = 0; i < pedidos.items.length; i++) {
let pedidosLength = pedidos.items.length;
let lengthPedidos = pedidos.nroPedCliente;
var boxClonado = $("#boxMaster").clone(true);
$(boxClonado).appendTo("#preparando").removeAttr("hidden", "style").removeAttr("id").addClass(`${pedidos.id}-${pedidos.items[i].codItem}`);
$(".nmroPedido").addClass(`${pedidos.items[i].codItem}`);
let nomeClasses = `${pedidos.id}-${pedidos.items[i].codItem}`;
let h3quantidade = `${pedidos.id}-${pedidos.items[i].codItem}`;
$("." + nomeClasses).append(`<p>${pedidos.items[i].codItem}</p>`);
$("." + h3quantidade).append(`<h3 class="h3qtd">${pedidos.items[i].qtdPedida}</h3>`);
//$("." + headerPedido).append(`Nº do Pedido: ${pedidos.nroPedido}`);
let data = new Date((pedidos.dataEntrega).substring(0, 10));
let dataEnt = ((data.getDate())) + "/" + ((data.getMonth() + 1)) + "/" + data.getFullYear();
}
}
As you can see, I managed to give a unique class to each box (that represent 1 item) at the end of the line:
$(boxClonado).appendTo("#preparando").removeAttr("hidden", "style").removeAttr("id").addClass(`${pedidos.id}-${pedidos.items[i].codItem}`);
And also managed to do it for the quantities as well. The point is, I'm not being able to do it with the <a class="nmroPedido" id="header>, as the code is printing all -${pedidos.items[i].codItem} codItem all at once in the same class, for every <a id="header> there is. Therefore, I can't set individual "nroPedido" for the box header.
Here's the array I'm getting from the fetch, in case that helps:
https://imgur.com/a/c10ER4X
What am I missing? How can I make it work?
This should do it. Just as example. You have a nested Object and you have to iterate through it with two each loops. Then you can append different unique id's. Then it's easy to create the correct HTML by JSON.
var arr = [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
}
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
}]
},
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
}
]
}
}
]
//console.log(arr);
var markup = '';
$.each(arr, function(key, value) {
key = key + 1;
markup += '<a class="nmroPedido-' + key + ' small-box-header" id="header-' + key + '"></a> <a class="float-right" id="dataEntrega">' + value.id + '</a>'
$.each(value.batters.batter, function(key, v) {
//console.log('id', v.id);
markup += ' <div class="inner"><p id="nomeproduto">' + v.type + '</p></div>';
});
});
$('#boxMaster').append(markup);
//console.log(markup);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="boxMaster"></div>

new persitent menu messenger node js

I am developing a bot in messenger, I need to change my previous persitent menu.
my old menu's code :
requestData = {
"setting_type": "call_to_actions",
"thread_state": "existing_thread",
"call_to_actions": [
{
"type": "postback",
"title": ......,
"payload": .....,
},
{
"type": "web_url",
"title": .....,
"url": ......,
},]};
but when I use the new form :
requestData = { "persistent_menu":[
{
"locale":"default",
"composer_input_disabled":true,
"call_to_actions":[
{
"title":.....,
"type":"nested",
"call_to_actions":[
{
"title":......,
"type":"postback",
"payload":......
},
]
},
]
},
{
"locale":"zh_CN",
"composer_input_disabled":false
}
]};
It doesn't work, I would be very grateful if you could help me.

C# ListItemCollection to JSON, while keeping values and text items

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

Get Child JSON Values from Objects

I have an endpoint with two JSON Objects as follows:
{
"main" {
"id": 1,
"title": Main Title,
},
{
"secondary" {
"id": 3,
"title": Secondary Title,
},
I am using backbone and have the following $each function, but using dot notation, I can't seem to be able to browse to the titles (ex. main.title or secondary.title). What am I missing?
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(response, function (index, value) {
console.log(value.main.title);
$("#test2").append('<li>' + value.main.title + '</li>');
});
In my console, it gives an error of: Uncaught TypeError: Cannot read property 'title' of undefined
Assuming your JSON is actually valid when returned (it isn't valid the way you show it), try
$("#test2").append('<li>' + value.title + '</li>');
Your actual JSON should look like:
{
"main": {
"id": 1,
"title": Main Title,
},
"secondary": {
"id": 3,
"title": Secondary Title,
}
}
If you just want the value of main, instead of using $.each(), remove that entire block and do:
$("#test2").append('<li>' + response.main.title + '</li>');
And your final code would look something like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
if (response.main.title !== 'undefined'){
$("#test2").append('<li>' + value.main.title + '</li>');
}else{
console.log('Main is undefined');
}
}
});
Final Edit: It looks like you want JSON like:
{
"main": [{
"id": 1,
"title": "Main Title"
}, {
"id": 2,
"title": "Main Title 2"
}, {
"id": 3,
"title": "Main Title 3"
}],
"secondary": [{
"id": 5,
"title": "Secondary Title 5"
}, {
"id": 34,
"title": "Secondary Title 34"
}, {
"id": 36,
"title": "Secondary Title 36"
}]
}
If that is the case your code would look like:
var collection = new contentArticles([], { id: urlid });
collection.fetch({
dataType: "json",
success: function (model, response) {
console.log(response);
$.each(function(index, value){
$.each(item_index, item_value){
$("#test2").append('<li>' + item_value.title + '</li>');
}
});
}
});
The problem lies with input JSON, it should be
{
"main" :{
"id": 1,
"title": "Main Title"
},
"secondary":{
"id": 3,
"title": "Secondary Title"
}
}

Custom Javascript Won't Run in Joomla

I am using Joomla-3 for my websites and I have created a simple small JavaScript(ajax) file which I attached through the template config file(as seen on the template's documentation).
I also added my html in an article(without TinyMCE etc so I know it accepts my code). The script works fine in a simple .html or .php file but it doesn't work along with Joomla.
My script has 2 dependent ajax dropdown menus(static content). Do you have any ideas on what could go wrong?
Thank you in advance!
PS. You can find the code of my JavaScript here.
Here's the code:
$(window).load(function () {
var services = [];
services['service1'] = [{
"name": "Giannis",
"url": "giannis"
}, {
"name": "Kostas",
"url": "kostas"
}, {
"name": "Fillipos",
"url": "fillipos"
}
];
services['service2'] = [{
"name": "Maria",
"url": "maria"
}, {
"name": "Peter",
"url": "peter"
}, {
"name": "Jack",
"url": "jack"
}
];
services['service3'] = [{
"name": "Dimitris",
"url": "dimitris"
}, {
"name": "Takis",
"url": "takis"
}, {
"name": "Gianna",
"url": "gianna"
}
];
jQuery(document).ready(function () {
jQuery("#services").change(function () {
var selectedService = $(this).val();
$('#doctors').children().remove();
$('#doctors').append('<option value="Null">Click to select a Doctor</option>');
jQuery.each(services[selectedService], function (ind, val) {
$('#doctors').append('<option value="' + this.url + '">' + this.name + '</option>');
})
});
jQuery("#doctors").change(function () {
var redirServ = $('#services option:selected').val();
var thePersonObject = services[redirServ];
var goThere = $(this).val();
var fullurl = 'http://www.website.com/our-services/' + redirServ + '/item/' + goThere;
alert(fullurl);
//location.href = 'http://www.website.com/our-services/' + redirServ + '/item/' + goThere;
});
});
});
Tried this?
$(window).on(‘load’, function(){
// AWESOMENESS
})

Categories

Resources