Autocomplete displays key and value using Alpaca forms - javascript

I'm using Alpaca forms to generate a form and one field will have an autocomplete. I'm testing Example 7 from http://www.alpacajs.org/docs/fields/text.html to see how this works. However, in my form the autocomplete displays as {"value":"Cloud CMS"} vs. Cloud CMS on the Alpaca site. I also tried directly specifying the autocomplete values as an array. Below is my code, note typeahead.js is installed locally.
<html>
<head>
<title>Alpaca-Autocomplete Form</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<link type="text/css" rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link type="text/css" href="http://code.cloudcms.com/alpaca/1.5.14/bootstrap/alpaca.min.css" rel="stylesheet" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js"></script>
<script type="text/javascript" src="http://code.cloudcms.com/alpaca/1.5.14/bootstrap/alpaca.min.js"></script>
<!-- typeahead.js https://github.com/twitter/typeahead.js -->
<script src="bower_components/typeahead.js/dist/bloodhound.min.js" type="text/javascript"></script>
<script src="bower_components/typeahead.js/dist/typeahead.bundle.min.js" type="text/javascript"></script>
</head>
<body>
<div id="field7"> </div>
<script>
var companies = ["Cloud CMS", "Amazon", "HubSpot"];
$("#field7").alpaca({
"schema": {
"type": "string"
},
"options": {
"type": "text",
"label": "Company Name",
"helper": "Select the name of a cloud computing company",
"typeahead": {
"config": {
"autoselect": true,
"highlight": true,
"hint": true,
"minLength": 1
},
"datasets": {
"type": "local",
"source": companies
// "source": function(query) {
// var companies = ["Cloud CMS", "Amazon", "HubSpot"];
// var results = [];
// for (var i = 0; i < companies.length; i++) {
// var add = true;
// if (query) {
// add = (companies[i].indexOf(query) === 0);
// }
// if (add) {
// results.push({
// "value": companies[i]
// });
// }
// }
// return results;
// }
}
}
}
});
</script>
</body>
</html>

I tried to play around with your code, the problem is the version of typeahead you are using. I changed the version to version 0.10.5 and it worked, try to use this version and tell me if it works.
Have a good day.

here's another solution if you want to use the latest version of Typeahead :
$("#field7").alpaca({
"schema": {
"type": "string"
},
"options": {
"type": "text",
"id": "companyField",
"label": "Company Name",
"helper": "Select the name of a cloud computing company"
}
});
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
var companies = ["Cloud CMS", "Amazon", "HubSpot"];
$('#companyField').typeahead({
hint: true,
highlight: true,
minLength: 2
}, {
name: 'companies',
source: substringMatcher(companies)
});
You have to add first a name or an id to your field and remove typeahead config from your alpaca code, then use the code provided by typeahead (link) to apply autocompletion to your field.
I you want to use the method with the previous version of typeahead you have to change the substringMatcher function like this :
// ...
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({
value: str
});
}
});
// ...
Here's a jsfiddle for this.
Using this technique I still have some styling issues, but I think there's is a workaround for this.

Related

Can i translate the Yes/No in a boolean switch slider from jquery?

I have a switch button slider with Yes/No option.
The following is the html file
<!DOCTYPE html>
<html lang="en">
<head>
<title>Yes/No or True/False question - Boolean question, jQuery Survey Library Example</title><meta name="viewport" content="width=device-width"/>
<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/survey-jquery#1.8.58/survey.jquery.min.js"></script>
<link href="https://unpkg.com/survey-core#1.8.58/modern.min.css" type="text/css" rel="stylesheet"/>
<link rel="stylesheet" href="./index.css"></head>
<body>
<div id="surveyElement" style="display:inline-block;width:100%;"></div>
<div id="surveyResult"></div>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
and the following javascript file
Survey
.StylesManager
.applyTheme("modern");
var json = {
questions: [
{
"type": "boolean",
"name": "bool",
"title": "Please answer the question",
"label": "Are you 21 or older?",
"isRequired": true
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (sender) {
document
.querySelector('#surveyResult')
.textContent = "Result JSON:\n" + JSON.stringify(sender.data, null, 3);
});
$("#surveyElement").Survey({model: survey});
I took the code from here.
Can i translate the Yes/No to Ja/Nein (German)?
There are no id's. So i cant use the replace function. Is this doable in some other way?
You need to use locale setting like this:
Survey
.StylesManager
.applyTheme("modern");
var json = {
locale: "de",
questions: [
{
"type": "boolean",
"name": "bool",
"title": "Please answer the question",
"label": "Are you 21 or older?",
"isRequired": true
}
]
};
window.survey = new Survey.Model(json);
survey
.onComplete
.add(function (sender) {
document
.querySelector('#surveyResult')
.textContent = "Result JSON:\n" + JSON.stringify(sender.data, null, 3);
});
$("#surveyElement").Survey({model: survey});
Here's a list of localizations that You can use:
https://github.com/surveyjs/surveyjs/tree/master/src/localization

JQuery autocomplete filter to search from beginning of line- input to display label but submit value

I have an array of towns - each town has a label and a value. Then there is an HTML input which should display the town label selected and on submit send the relevant value. A JQuery script with a filter that chooses the town based on the beginning characters of the label and not the characters in the rest of the label body. I need the script to, filter as designed, but when a town is selected, the HTML id #dtags must display the label and the #dtag must submit the value via a hidden input.
I have two scripts, each one does ONE of the above successfully, but I am battling to get one script to combine both "features".
I am looking for some assistance to create a single JQuery script to achieve the above. My JQuery skills are limited and the code below is what I have managed to find through searching and adapting - credit to the originators.
Please see code below:-
<div class="ui-widget">
<input id="dtags" class="form-control col-md-8" placeholder="Choose Delivery Town" required>
<input id="dtag" type="hidden" name="deltown">
</div>
<script>
(function() {
var towns = [
{ "label": "AANDRUS, Bloemfontein", "value": 1 },
{ "label": "AANHOU WEN, Stellenbosch", "value": 2 },
{ "label": "ABBOTSDALE, Western Cape", "value": 3 },
{ "label": "ABBOTSFORD, East London", "value": 4 },
{ "label": "ABBOTSFORD, Johannesburg", "value": 5 },
{ "label": "ABBOTSPOORT, Limpopo", "value": 6 },
{ "label": "ABERDEEN, Eastern Cape", "value": 7 },
{ "label": "ACKERVILLE, Witbank", "value": 8 },
{ "label": "ACORNHOEK, Mphumalanga", "value": 9 },
{ "label": "ACTIVIA PARK, Germiston", "value": 10 }
];
$("#dtags").autocomplete({
source: towns
});
// Overrides the default autocomplete filter function to search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
})();
//Uses event.preventDefault(); to halt the default and works as below
// $("#dtags").autocomplete({
//minLength: 1,
//source: towns,
//select: function(event, ui) {
//event.preventDefault();
//$("#dtags").val(ui.item.label);
//$("#dtag").val(ui.item.value);
//}
//});
//});
//});
//});
</script>
In case this could help anyone in the future, this is the script that I managed to get working successfully as per the question - slight change as to using an external data source:-
<script>
(function() {
var towns = [<?php require_once("towns.txt")?>];
$("#dtags").autocomplete({
source: towns,
select: function( event, ui ) {
$("#dtags").val(ui.item.label);
$("#dtag").val(ui.item.value);
return false;
}
});
// Overrides the default autocomplete filter function to search only from the beginning of the string
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
})();
</script>

Create a single VCard file with multiple entries using javascript

I used the code from this github gist that allows you to save a single content into a VCF file.
<!doctype html>
<html>
<head>
<script type="text/javascript" src="vcard2.js"></script>
</head>
<script type="text/javascript">
// From JSON
var johnSmith = {
"version": "4.0",
"n": "SMITH;John;;",
"fn": "John Smith",
"nickname":"js",
"title": "Missing man too",
"tel": [
{"value": "555-555-555", "type": "cell"}
],
"email": [
{ "value": "john.smith#work.com", "type": "work" },
{ "value": "john.smith#home.com", "type": "home" }
]
}
var link = vCard.export(johnSmith, "John Smith", false) // use parameter true to force download
document.body.appendChild(link)
</script>
</body>
</html>
This worked for single content as file see JSfiddle.
My question is how to add multiple contents into same VCF file.
In the fiddle you provided just edit the dump() function to accept array. Then iterate the array and perform the exact same operations, combining the output (split with \n) into one variable.
dump: function(cards) {
var cardsLength = cards.length;
var cardsStr = "";
for (var cardsIndex = 0; cardsIndex < cardsLength; cardsIndex++) {
var card = cards[cardsIndex];
//...existing code... just remove the return
cardsStr+=str+"\n";
}
return cardsStr;
}
Now call vCard.export() and pass an array of objects instead of object.
Try it here: JSFiddle

Custom Match Formula for EasyAutocomplete

I'm using a JS plugin called EasyAutocomplete to handle advanced autosuggestion on my website. It supports remote data sets (JSON, XML, plain text) and uses ajax method calls to search, sort and match the response phrase.
I'm trying to write a custom match formula, which it allows me to do, but would love some help writing this out.
Right now, as you type, it searches for any part of a word/phrase for what you're typing. I'd like to have it only check the beginning of each word in a single or multi-word phrase.
Let's say my remote data set contains:
"Market Street"
"Market Thestreet Lane"
"Street South Road"
If my search is "Street", by the plugin's default functionality, all 3 results will show, because the word "street" is part of each of those 3 results. (Demo Below)
I found a similar question to mine on the plugin's Github repo (and the answer from the plugin author), but that question was for matching only the beginning of each result item (not each word in each result item). So if my search is "Street", only the third result will show. (Demo Below)
My question is for a match formula that searches the beginning of any word in a result item. So, if my search is "Street", the first and third result will show.
Here is how the plugin functions by default (I've commented out the custom match formula):
jQuery(document).ready(function($) {
var options = {
data: [
{"name": "Market Street", "parent": "Dog Management", "link": "https://marketstreet.com"},
{"name": "Market Thestreet Lane", "parent": "Dog Management", "link": "https://marketlane.com"},
{"name": "Street South Road", "parent": "Cat Management", "link": "https://streetsouthroad.com"}
],
getValue: "name",
list: {
match: {
enabled: true,
/*
method: function(element, phrase) {
if(element.indexOf(phrase) === 0) {
return true;
} else {
return false;
}
}
*/
},
onSelectItemEvent: function() {
var selectedItemValue = $("#companies").getSelectedItemData().parent;
var selectedItemLink = $("#companies").getSelectedItemData().link;
$("#company_result").html('Contact '+selectedItemValue+'').trigger("change");
},
},
template: {
type: "description",
fields: {
description: "parent"
}
}
};
$("#companies").easyAutocomplete(options);
});
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css'>
<link rel='stylesheet' href='https://d3vv6lp55qjaqc.cloudfront.net/items/040r1I2Y1K3T3w3L3i3E/easy-autocomplete.css'>
<script src='https://code.jquery.com/jquery-1.11.2.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script src='https://d3vv6lp55qjaqc.cloudfront.net/items/2Q0s1P3D0D2i3u0M1m1x/jquery.easy-autocomplete.min.js'></script>
<div class="container">
<br>
<div class="row">
<div class="col-md-8 col-offset-3">
<p>Search for "Street"</p>
<form style="text-align: center; margin: 0 auto;" onkeypress="return event.keyCode != 13;">
<input class="form-control" id="companies" placeholder="Type your resort property name..."/>
<div id="company_result"></div>
</form>
</div>
</div>
</div>
Here is that custom match formula that only matches if the result item begins with the search phrase:
jQuery(document).ready(function($) {
var options = {
data: [
{"name": "Market Street", "parent": "Dog Management", "link": "https://marketstreet.com"},
{"name": "Market Thestreet Lane", "parent": "Dog Management", "link": "https://marketlane.com"},
{"name": "Street South Road", "parent": "Cat Management", "link": "https://streetsouthroad.com"}
],
getValue: "name",
list: {
match: {
enabled: true,
method: function(element, phrase) {
if(element.indexOf(phrase) === 0) {
return true;
} else {
return false;
}
}
},
onSelectItemEvent: function() {
var selectedItemValue = $("#companies").getSelectedItemData().parent;
var selectedItemLink = $("#companies").getSelectedItemData().link;
$("#company_result").html('Contact '+selectedItemValue+'').trigger("change");
},
},
template: {
type: "description",
fields: {
description: "parent"
}
}
};
$("#companies").easyAutocomplete(options);
});
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css'>
<link rel='stylesheet' href='https://d3vv6lp55qjaqc.cloudfront.net/items/040r1I2Y1K3T3w3L3i3E/easy-autocomplete.css'>
<script src='https://code.jquery.com/jquery-1.11.2.min.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
<script src='https://d3vv6lp55qjaqc.cloudfront.net/items/2Q0s1P3D0D2i3u0M1m1x/jquery.easy-autocomplete.min.js'></script>
<div class="container">
<br>
<div class="row">
<div class="col-md-8 col-offset-3">
<p>Search for "Street"</p>
<form style="text-align: center; margin: 0 auto;" onkeypress="return event.keyCode != 13;">
<input class="form-control" id="companies" placeholder="Type your resort property name..."/>
<div id="company_result"></div>
</form>
</div>
</div>
</div>
Thank you!
method: function(element, phrase) {
return !!element.toLowerCase().split(" ").filter((word) => word.indexOf(phrase.toLowerCase()) === 0).length;
}
This function:
Makes the element lowercase (no capitalization woes)
Splits it into its words
Filters out any words that don't start with the given input
If the filtered array has any elements in it, it must match. Otherwise, it doesn't. That's what the .length check there is for.

for json Element id = "1" , append ul 'chapter_count' times

I am fairly new to web dev and This is my first question on StackOverflow. Apologies if I didn't frame it properly.
Here is my json.
{
"books":
[
{
"_id": "1",
"book_cat": "OLD",
"book_eng_name": "Book1",
"chapter_count": "50"
},
{
"_id": "2",
"book_cat": "OLD",
"book_eng_name": "Book2",
"chapter_count": "40""
}
]
I want to use this json with jquery to append to . First I need to filter __id and then append a statement to the <ul> "Chapter_count" times.
For instance, if I select I am searching for _id 1 I want 50 item list that says
Chapter 1
Chapter 2
...
...
...
Chapter 50
I want to append to ul in the following html:
<html>
<title>Chapters</title>
<body>
<ul></ul>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/
jquery.min.js"></script>
<script type = "text/javascript" src='files/js/Chapter_script.js'></script>
<script type = "text/javascript" src='files/js/books.json'></script>
</body>
</html>
I wrote something like this but didn't work :(
(document).ready(function(){
var search_id = window.location.search;
var chapter_no = search_id.match(/\d+/g);
$.getJSON("files/js/books.json",function(data){
$.each(data.books, function(){
if (this['_id'] == chapter_no ){
for(var i = 0; i <= this['chapter_count']; i++; ){
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
};
})
});
});
Where chapter_no is extracted from url with window.location.search
Sample url: http://localhost:90/chapters.html?book_id=1
Thanks in advance.
Copy the below code in $.getJSON("files/js/books.json",function(data) function.
var selectedElement = $.grep(data.books, function( element, index ) {
if(chapter_no == element._id)
return element
});
for(var i =0 ; i<=selectedElement[0].chapter_count;i++)
{
$("ul").append("<li>Chapter Number"+i+"</li></br>")
}
first your json is not valid and have syntax error i think the true one is
json ={ "books": [ { "_id": "1", "book_cat": "OLD", "book_eng_name": "Book1",
"chapter_count": "50" }, { "_id": "2", "book_cat": "OLD",
"book_eng_name": "Book2", "chapter_count": "40" } ]}
its sample js code
json.books.forEach(function (b){
if(b._identer code here == "1")
{
for(var i =0 ; i<=b.caphter_count;i++)
{
//put your code here
}
}
})

Categories

Resources