forEach works fine in onClick but not without - javascript

When I try to append an <li> attribute to the list of servers, it isn't executing the forEach() - I tried console.log() nested but it ignores it like the Servers is an empty array?
$(function() {
var Discord = {
Servers: [{
Name: 'Server 1',
Link: 'hidden for security'
}, {
Name: 'Server 2',
Link: 'hidden for security'
}]
};
$('#_discord_notify_btn').click(function() {
Discord.Servers.forEach(function($server) {
$.post($server.Link, {
content: $('#_discord_notify').val()
});
});
});
// this code is ignored??
Discord.Servers.forEach(function($server) {
$('_discord_servers ul').append("<li>" + $server.Name + "</li>");
});
});
textarea {
min-width: 447px;
min-height: 110px;
}
button {
border: 1px solid #000;
border-radius: 9px;
background: none;
padding: 10px;
}
button:hover {
background: #000;
color: #fff;
border: 1px solid #fff;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='_discord_servers'>
<b>Servers you're notifying</b>
<ul></ul>
</div>
<textarea id='_discord_notify'>Enter your notification...</textarea>
<button type='button' id='_discord_notify_btn'>
Send Notification
</button>

Looks like you're missing the # for the ID selector in your second example.
// this code is ignored??
Discord.Servers.forEach(function($server) {
$('#_discord_servers ul').append("<li>" + $server.Name + "</li>");
});

You're missing the id selector:
$(function() {
var Discord = {
Servers: [{
Name: 'Server 1',
Link: 'hidden for security'
}, {
Name: 'Server 2',
Link: 'hidden for security'
}]
};
$('#_discord_notify_btn').click(function() {
Discord.Servers.forEach(function($server) {
$.post($server.Link, {
content: $('#_discord_notify').val()
});
});
});
// this code is ignored??
Discord.Servers.forEach(function($server) {
console.log('test');
$('#_discord_servers ul').append("<li>" + $server.Name + "</li>");
});
});
textarea {
min-width: 447px;
min-height: 110px;
}
button {
border: 1px solid #000;
border-radius: 9px;
background: none;
padding: 10px;
}
button:hover {
background: #000;
color: #fff;
border: 1px solid #fff;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='_discord_servers'>
<b>Servers you're notifying</b>
<ul></ul>
</div>
<textarea id='_discord_notify'>Enter your notification...</textarea>
<button type='button' id='_discord_notify_btn'>
Send Notification
</button>

Related

Pass HTML code as CSS content using JavaScript

I have a jQuery function like below.
function resultfucntion(state) {
if (!state.id) {
return state.text;
}
var state_output = $("<span data-tooltip='"+state.value +"'>" + state.text +
"<span>(" + state.text1 + ")</span></span>"
);
return state_output;
}
I would like to pass HTML code as content value to below CSS code
span:hover:before {
content: attr(data-tooltip);
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
I am getting output like below
I read this post.
Now I am looking for a JavaScript or jQuery way to pass HTML value as CSS content.
I'm not quite sure if it's possible to do it the way you want it. But this may be a solution how you could achieve the same goal:
$('span').hover(function() {
$(this).after(`<div class="tooltip-box">${$(this).attr('data-tooltip')}</div>`);
$('.tooltip-box').show();
}, function() {
$('.tooltip-box').hide();
});
.tooltip-box {
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-tooltip="I am <strong>strong</strong>, <em>emphasized</em> and <mark>marked</mark>.">Hyperlink</span>
Update
It is not clear to me what the point of your function should be. However, this is how you could combine the above code with your function:
function resultfucntion(state) {
if (!state.id) {
return state.text;
}
var state_output = `<span data-tooltip='${state.value}'>${state.text}<span>(${state.text1})</span></span>`;
return state_output;
}
const state = {
id: 1,
value: 'I am <strong>strong</strong>, <em>emphasized</em> and <mark>marked</mark>.',
text: 'Hyperlink',
text1: 1
}
$('body').append(resultfucntion(state));
$('span').hover(function() {
$(this).after(`<div class="tooltip-box">${$(this).attr('data-tooltip')}</div>`);
$('.tooltip-box').show();
}, function() {
$('.tooltip-box').hide();
});
.tooltip-box {
position: absolute;
padding: 5px 10px;
margin: -3px 0 0 180px;
background: orange;
color: white;
border-radius: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Vue.js custom select component with v-model

I want to create a custom select component in Vue.js. Since I need specific options styling, I need to create 'select' made of div's etc that looks and acts like a real html select.
Currently I have something like this:
Vue.component('child', {
template: `<div class="component-container" #click="showOptions = !showOptions">
<div class="component__select">
<span class="component__select--name">Select Fruit</span>
<span class="c-arrow-down" v-if="!showOptions"></span>
<span class="c-arrow-up" v-if="showOptions"></span>
</div>
<ul class="component__select-options" v-if="showOptions" >
<li class="select--option" v-for="option in options">
<label> <input type="checkbox" :value="option"/> {{option.name}}</label>
</li>
</ul>
</div>`,
methods: {
selectOption(option) {
this.$emit('option', option)
}
},
data: () => ({
showOptions: false,
}),
props: ['options']
});
var vm = new Vue({
el: '#app',
data: () => ({
options: [
{id: 0, name: 'Apple'},
{id: 1, name: 'Banana'},
{id: 2, name: 'Orange'},
{id: 2, name: 'Strawberry'},
],
selectedFruit: ''
}),
})
.component__select {
height: 38px;
background-color: #F5F7FA;
border: 1px solid #dddddd;
line-height: 38px;
display: grid;
max-width: 500px;
grid-template-columns: 10fr 1fr;
}
.component__select--name {
font-size: 0.8rem;
padding: 0 0 0 25px;
cursor: pointer;
}
.c-arrow-down {
justify-self: end;
}
.component__select-options {
max-height: 180px;
border: 1px solid #dddddd;
border-top: none;
overflow: auto;
position: absolute;
z-index: 1500;
max-width: 500px;
width: 500px;
margin: 0;
padding: 0;
}
.select--option {
height: 35px;
display: grid;
align-content: center;
padding: 0 0 0 25px;
background-color: #f5f5fa;
border-bottom: 1px solid #dddddd;
}
.select--option:last-child {
border-bottom: none;
}
.select--option:nth-child(2n) {
background-color: #ffffff;
}
.select--option input{
display: none;
}
.single-option {
height: 55px;
background-color: #2595ec;
font-size: 0.8rem;
border: 1px solid red;
}
.cust-sel {
width: 200px;
height: 38px;
background-color: #f5f5fa;
border: 1px solid #dddddd;
}
.cust-sel:focus {
outline-width: 0;
}
<html>
<head>
<title>An example</title>
</head>
<body>
<div id="app">
<span> This is parent component</span>
<p>I want to have data from select here: "{{selectedFruit}}"</p>
<child :options="options" v-model="selectedFruit"></child>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</body>
</html>
But my problem is now how to return data from child to parent component using v-model on child component.
(I know I could emit data from child component and do:
<custom-select :options="someOptions" #selected="setSelectedOption"/>
but I need it to be reusable and writing more and more methods to retrieve data from every select in parent component is not exactly how it should work I think.)
Also I need to have an entire object returned, not only ID. (that's why i've got :value="option")
Any ideas?
As Vue Guide said:
v-model is essentially syntax sugar for updating data on user input
events, plus special care for some edge cases.
The syntax sugar will be like:
the directive=v-model will bind value, then listen input event to make change like v-bind:value="val" v-on:input="val = $event.target.value"
So for your use case, you need to create one prop=value, then emit the selected option with event=input.
Like below demo (bind/emit the whole option object):
Vue.config.productionTip = false
Vue.component('child', {
template: `<div class="component-container" #click="showOptions = !showOptions">
<div class="component__select">
<span class="component__select--name">{{value ? value.name : 'Select Fruit'}}</span>
<span class="c-arrow-down" v-if="!showOptions"></span>
<span class="c-arrow-up" v-if="showOptions"></span>
</div>
<ul class="component__select-options" v-if="showOptions" >
<li class="select--option" v-for="option in options" #click="selectOption(option)">
<label> <input type="checkbox" :value="option"/> {{option.name}}</label>
</li>
</ul>
</div>`,
methods: {
selectOption(option) {
this.$emit('input', option)
}
},
data: () => ({
showOptions: false
}),
props: ['options', 'value']
});
var vm = new Vue({
el: '#app',
data: () => ({
options: [
{id: 0, name: 'Apple'},
{id: 1, name: 'Banana'},
{id: 2, name: 'Orange'},
{id: 2, name: 'Strawberry'},
],
selectedFruit: ''
}),
})
.component__select {
height: 38px;
background-color: #F5F7FA;
border: 1px solid #dddddd;
line-height: 38px;
display: grid;
max-width: 500px;
grid-template-columns: 10fr 1fr;
}
.component__select--name {
font-size: 0.8rem;
padding: 0 0 0 25px;
cursor: pointer;
}
.c-arrow-down {
justify-self: end;
}
.component__select-options {
max-height: 180px;
border: 1px solid #dddddd;
border-top: none;
overflow: auto;
position: absolute;
z-index: 1500;
max-width: 500px;
width: 500px;
margin: 0;
padding: 0;
}
.select--option {
height: 35px;
display: grid;
align-content: center;
padding: 0 0 0 25px;
background-color: #f5f5fa;
border-bottom: 1px solid #dddddd;
}
.select--option:last-child {
border-bottom: none;
}
.select--option:nth-child(2n) {
background-color: #ffffff;
}
.select--option input{
display: none;
}
.single-option {
height: 55px;
background-color: #2595ec;
font-size: 0.8rem;
border: 1px solid red;
}
.cust-sel {
width: 200px;
height: 38px;
background-color: #f5f5fa;
border: 1px solid #dddddd;
}
.cust-sel:focus {
outline-width: 0;
}
<script src="https://unpkg.com/vue#2.5.16/dist/vue.js"></script>
<div id="app">
<span> This is parent component</span>
<p>I want to have data from select here: "{{selectedFruit}}"</p>
<child :options="options" v-model="selectedFruit"></child>
</div>
When using v-model on custom component all you need is to declare a prop named 'value' and when you need the component to chance it emit an 'input' event.
Something like this:
<template>
<form #submit.prevent="$emit('onSearch',val)" class="form-perfil">
<div class="form-group col-md-12">
<input v-model="val" #input="$emit('input',val)"
placeholder="filtrar resultados" class="form-control">
</div>
</form>
</template>
<script>
module.exports = {
name: "CaixaFiltro",
props: ["value"],
data: _ => ({ val: "" }),
created() {
this.val = this.value
}
}
</script>
Then you can use (after register the component) it like this:
<caixa-filtro v-model="textoBusca" #onSearch="listar"></caixa-filtro>
You can find more detailed info there:

Get specific data from an jQuery $(this) object

I have a node tree and want to fetch certain data attributes from these nodes when clickin on them.
I can't figure out how to get the right data from the object recived when clicking on it.
var simple_chart_config = {
chart: {
container: "#tree"
},
nodeStructure: {
text: {
name: "King Miro",
title: "King"
},
children: [{
text: {
name: "King Randor",
title: "King"
},
children: [{
text: {
name: "He-Man",
title: "Master of the Universe"
},},{
text: {
name: "She-Ra",
title: "Princess"
},
}]
}, {
text: {
name: "Skeletor",
title: "Lord of Destruction"
},
}, ]
}
}
var my_chart = new Treant(simple_chart_config);
$('body').on('click', '.Treant .node', function() {
alert($(this).attr("title"));
console.log($(this));
});
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }
body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }
.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.js"></script>
<div id="tree">
</div>
So now I'm trying to fetch the name: and title:
I tried with many different versions of $(this).attr("") and val(). Trying to fetch via div class and similar.
I'm stuck right now.
You can use your build DOM to take the correct text that you need : $(this).find(".node-name") and $(this).find(".node-title")
var simple_chart_config = {
chart: {
container: "#tree"
},
nodeStructure: {
text: {
name: "King Miro",
title: "King"
},
children: [{
text: {
name: "King Randor",
title: "King"
},
children: [{
text: {
name: "He-Man",
title: "Master of the Universe"
},},{
text: {
name: "She-Ra",
title: "Princess"
},
}]
}, {
text: {
name: "Skeletor",
title: "Lord of Destruction"
},
}, ]
}
}
var my_chart = new Treant(simple_chart_config);
$('body').on('click', '.Treant .node', function() {
alert($(this).find(".node-name").text());
alert($(this).find(".node-title").text());
console.log($(this));
});
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:''; }
abbr,acronym { border:0; }
body { background: #fff; }
/* optional Container STYLES */
.chart { height: 600px; margin: 5px; width: 900px; }
.Treant > .node { padding: 3px; border: 1px solid #484848; border-radius: 3px; }
.Treant > .node img { width: 100%; height: 100%; }
.Treant .collapse-switch { width: 100%; height: 100%; border: none; }
.Treant .node.collapsed { background-color: #DEF82D; }
.Treant .node.collapsed .collapse-switch { background: none; }
<link href="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/treant-js/1.0/Treant.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.js"></script>
<div id="tree">
</div>

JQuery selectable functions [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
can anyone help me with my js selector functions? The problem is the color and size indicator numbers showing do not default back to "blank" after mouseout. I want the indicator number to disappear after mouseout if a mouseclick never happens over the function. Can anyone help? My demo http://jsfiddle.net/jwjxr2oh/3/
Thanks
The problem is when sizeIndicator.data('selected') is not present sizeIndicator.data('selected') will return undefined, then the text() method will act like a getter method and will not update the value to blank so
$(function() {
var colorsList = $('#colors');
var sizesList = $('#sizes');
var colorIndicator = $('#color_indicator');
var sizeIndicator = $('#size_indicator');
var colors = [{
id: 1,
name: 'Dark Blue Denim',
color: '#0B3861'
}, {
id: 2,
name: 'Light Blue Denim',
color: '#81BEF7'
}];
var sizes = [{
id: 1,
name: '26'
}, {
id: 2,
name: '28'
}, {
id: 2,
name: '30'
}, {
id: 3,
name: '32'
}];
$.each(colors, function() {
colorsList.append(
$('<li>').attr({
id: 'color_' + this.id
})
.data('info', this)
.append(
$('<div>').css('background-color', this.color)));
});
$.each(sizes, function() {
sizesList.append(
$('<li>').attr({
id: 'size_' + this.id
})
.data('info', this)
.text(this.name)
.addClass('text'));
});
colorsList.selectable({
selected: function(event, ui) {
var total = $(ui.selected).siblings('li.ui-selected').length + 1;
if (total > 1) {
$(ui.selected).removeClass('ui-selected');
} else {
var color = $(ui.selected).data('info').name;
colorIndicator.data('selected', color).text(color);
}
}
});
sizesList.selectable({
selected: function(event, ui) {
var total = $(ui.selected).siblings('li.ui-selected').length + 1;
if (total > 1) {
$(ui.selected).removeClass('ui-selected');
} else {
var size = $(ui.selected).data('info').name;
sizeIndicator.data('selected', size).text(size);
}
}
});
sizesList.children('li').hover(function() {
sizeIndicator.text($(this).data('info').name);
}, function() {
console.log(sizeIndicator)
sizeIndicator.text(sizeIndicator.data('selected') || '');
});
colorsList.children('li').hover(function() {
colorIndicator.text($(this).data('info').name);
}, function() {
colorIndicator.text(colorIndicator.data('selected') || '');
});
$('#show').click(function() {
var color = colorsList.find('li.ui-selected').eq(0).data('info');
var size = sizesList.find('li.ui-selected').eq(0).data('info');
if (typeof color != 'undefined') {
alert('Color selected: ' + color.name + ', id: ' + color.id);
}
if (typeof size != 'undefined') {
alert('Size selected: ' + size.name + ', id: ' + size.id);
}
});
});
.selectable li.ui-selecting {} .selectable li.ui-selected {
border: 1px solid #000;
}
.selectable {
list-style-type: none;
margin: 0;
padding: 0;
}
.selectable li {
border: 1px solid #fff;
margin: 3px;
padding: 3px;
float: left;
text-align: center;
}
.selectable li:hover {
border: 1px solid #000;
margin: 3px;
padding: 3px;
cursor: pointer;
cursor: hand;
float: left;
text-align: center;
}
.selectable li div {
border: 1px solid #000;
padding: 5px;
margin: 3px;
width: 20px;
height: 20px;
}
.selectable li.text {
color: #000;
padding: .5em .5em;
margin: .5em 1em;
font-size: 1.5em;
border-radius: 50%;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
line-height: 1em;
}
.selectable li.text:hover {
cursor: pointer;
cursor: hand;
color: #000;
font-weight: normal;
border: 1px solid #000;
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<input type='button' id='show' value='What is selected?'>
<table width="595" height="172" border="0">
<tr>
<td width="421" height="40" align="center" valign="middle">Size: <span id="size_indicator"></span>
</td>
<td width="164">Color: <span id="color_indicator"></span></td>
</tr>
<tr>
<td height="103">
<ol id="sizes" class='selectable'></ol>
</td>
<td>
<ol id="colors" class='selectable'></ol>
</td>
</tr>
</table>

Typeahead.js - Unable to choose suggestion

I must be an idiot. I am using the Typeahead.js plugin. I am trying to use custom templates for suggestions. While my custom templates appear, I cannot use the arrow-keys to actually select an item. If I hover over an item, the selection doesn't get highlighted either. I thought it might be just a styling issue. However, if 3 suggestions appear, and I click the down arrow twice, then enter, my selected option does not appear in the text box. Alternatively, if I choose an option with my mouse, the option does not appear in the box.
What am I doing wrong? Currently, I have the following:
var suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/suggests?querytext=%QUERY',
filter: function(results) {
return $.map(results.Results, function(suggestion) {
return suggestion;
});
}
});
suggestions.initialize();
$(document).ready(function() {
$('input.typeahead').typeahead(
{ minLength: 3 },
{
name: 'suggestions',
source: suggestions.ttAdapter(),
templates: {
suggestion: function(data) {
var str = '';
if (data.Type === 'Customer') {
str += '<i class="icon-1"></i>';
} else if (data.Type === 'Product') {
str += '<i class="icon-2"></i>';
}
str += '<div>' + data.Name + '</div>';
return str;
}
}
}
);
});
The suggestions popup. The results come from the following JSON:
{
"Results":[
{
"Type":"Customer",
"Id":5,
"Name":"Bill",
"LastUpdated":"01-01-2015"
},
{
"Type":"Customer",
"Id":135,
"Name":"Billows",
"LastUpdated":"01-02-2015",
},
{
"Type":"Product",
"Id":241,
"Name":"Bill Check",
"LastUpdate":"01-04-2015"
}
],
"TotalResults":3,
"TotalCustomers":2,
"TotalProducts":1
}
How do I a) Apply a highlight to an item when a use hovers over an item with the mouse or uses the arrow keys to get to it b) Put the select item's Name value in the input box when the suggestion is selected?
Thanks!
Try
$(function () {
var suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/api/suggests?querytext=%QUERY',
filter: function(results) {
return $.map(results.Results, function(suggestion) {
return {value:suggestion.Name, suggest:suggestion};
});
}
});
suggestions.initialize();
$("#bloodhound .typeahead").typeahead({
minLength: 3,
hint: true,
highlight: true
}, {
name: 'suggestions',
displayKey: 'value',
templates: {
suggestion: function(data) {
var str = '';
if (data.suggest.Type === 'Customer') {
str += '<i class="icon-1">' + data.suggest.Type + '</i>';
} else if (data.suggest.Type === 'Product') {
str += '<i class="icon-2">' + data.suggest.Type + '</i>';
}
str += '<div>' + data.value + '</div>';
return str;
}
},
source: suggestions.ttAdapter()
});
})
$(function () {
var data = {
"Results":[
{
"Type":"Customer",
"Id":5,
"Name":"Bill",
"LastUpdated":"01-01-2015"
},
{
"Type":"Customer",
"Id":135,
"Name":"Billows",
"LastUpdated":"01-02-2015",
},
{
"Type":"Product",
"Id":241,
"Name":"Bill Check",
"LastUpdate":"01-04-2015"
}
],
"TotalResults":3,
"TotalCustomers":2,
"TotalProducts":1
};
var suggestions = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: $.map(data.Results, function(d) {
return {value:d.Name, suggest:d}
})
});
suggestions.initialize();
$("#bloodhound .typeahead").typeahead({
minLength: 3,
hint: true,
highlight: true
}, {
name: 'suggestions',
displayKey: 'value',
templates: {
suggestion: function(data) {
var str = '';
if (data.suggest.Type === 'Customer') {
str += '<i class="icon-1">'+data.suggest.Type+'</i>';
} else if (data.suggest.Type === 'Product') {
str += '<i class="icon-2">'+data.suggest.Type+'</i>';
}
str += '<div>' + data.value + '</div>';
return str;
}
},
source: suggestions.ttAdapter()
});
})
#font-face {
font-family:"Prociono";
src: url("../font/Prociono-Regular-webfont.ttf");
}
html {
overflow-y: scroll;
}
.container {
margin: 0 auto;
max-width: 750px;
text-align: center;
}
.tt-dropdown-menu, .gist {
text-align: left;
}
html {
color: #333333;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
line-height: 1.2;
}
.title, .example-name {
font-family: Prociono;
}
p {
margin: 0 0 10px;
}
.title {
font-size: 64px;
margin: 20px 0 0;
}
.example {
padding: 30px 0;
}
.example-name {
font-size: 32px;
margin: 20px 0;
}
.demo {
margin: 50px 0;
position: relative;
}
.typeahead, .tt-query, .tt-hint {
border: 2px solid #CCCCCC;
border-radius: 8px 8px 8px 8px;
font-size: 24px;
height: 30px;
line-height: 30px;
outline: medium none;
padding: 8px 12px;
width: 396px;
}
.typeahead {
background-color: #FFFFFF;
}
.typeahead:focus {
border: 2px solid #0097CF;
}
.tt-query {
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset;
}
.tt-hint {
color: #999999;
}
.tt-dropdown-menu {
background-color: #FFFFFF;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 8px 8px 8px 8px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
margin-top: 12px;
padding: 8px 0;
width: 422px;
}
.tt-suggestion {
font-size: 18px;
line-height: 24px;
padding: 3px 20px;
}
.tt-suggestion.tt-cursor {
background-color: #0097CF;
color: #FFFFFF;
}
.tt-suggestion p {
margin: 0;
}
.gist {
font-size: 14px;
}
.example-twitter-oss .tt-suggestion {
padding: 8px 20px;
}
.example-twitter-oss .tt-suggestion + .tt-suggestion {
border-top: 1px solid #CCCCCC;
}
.example-twitter-oss .repo-language {
float: right;
font-style: italic;
}
.example-twitter-oss .repo-name {
font-weight: bold;
}
.example-twitter-oss .repo-description {
font-size: 14px;
}
.example-sports .league-name {
border-bottom: 1px solid #CCCCCC;
margin: 0 20px 5px;
padding: 3px 0;
}
.example-arabic .tt-dropdown-menu {
text-align: right;
}
[class|=icon] {
color:orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<div id="bloodhound">
<input class="typeahead" type="text" placeholder="Customers and Products" />
</div>
Have you tried adding a valueKey to your function pointing it to name? See SO answer here:
Typeahead.js does give me suggestions but doesn't select them

Categories

Resources