Create a single VCard file with multiple entries using javascript - 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

Related

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
}
}
})

Javascript - How parse each json object as text string

I have my html working with javascript, and the file manifest.json to be read.
Here is my json file's code:
{
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer": {
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": 1,
"default_language": "en"
}
I need read each object as text, parsing in javascript. Example:
<h1>+ name +</h1>
<h2>+ description +</h2>
<img src="+ icon +"/>
<p>+ version +</p>
Too, how can I read sub-objects of "developer" object?
EDIT: Validated json. Thanks to #ADreNaLiNe-DJ and Curious Concept's JSON Formater for helping validate.
You might do like the following. It will get your object key value pairs flattened even if you have nested objects in your data structure.
var data = {
"name": "Project",
"description": "A template project",
"icon": "img/icon.svg",
"version": "X.X.X.X",
"developer":
{
"name": "Daniell Mesquita",
"url": "http://about.me/daniellmesquita"
},
"shop_id": "1",
"manifest_version": "1",
"default_language": "en",
},
stack = [[],[]];
function getKeyValuePairs(obj,stack) {
Object.keys(obj).forEach( e => obj[e] instanceof Object ? getKeyValuePairs(obj[e], stack) : (stack[0].push(e), stack[1].push(obj[e])));
}
getKeyValuePairs(data, stack);
document.write("<pre>" + JSON.stringify(stack,null,2) + "</pre>");
If the json is in a String variable convert it to an object. Then you can access the single values:
var obj = JSON.parse(jsonString);
var name = obj.name;
var version = obj.version;
var developerName = obj.developer.name;
Well you can use
yourJsonVarName.developer.name
yourJsonVarName.developer.url
try this!
Added
If your external file is in your domain maybe you can use this to retrieve your data inside json file.
$.getJSON( "manifest.json", function( data ) {
var name = data.developer.name;
var url = data.developer.url;
});

Is it possible to access a json array element without using index number?

I have the following JSON:
{
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]}
}
I want to access "value" of the the array element with "fieldName": "telNum" without using index numbers, because I don't know everytime exactly at which place this telNum element will appear.
What I dream of is something like this:
jsonVarName.responseObject.fields['fieldname'='telNum'].value
Is this even possible in JavaScript?
You can do it like this
var k={
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}};
value1=k.responseObject.fields.find(
function(i)
{return (i.fieldName=="telNum")}).value;
console.log(value1);
There is JSONPath that lets you write queries just like XPATH does for XML.
$.store.book[*].author the authors of all books in the store
$..author all authors
$.store.* all things in store, which are some books and a red bicycle.
$.store..price the price of everything in the store.
$..book[2] the third book
$..book[(#.length-1)]
$..book[-1:] the last book in order.
$..book[0,1]
$..book[:2] the first two books
$..book[?(#.isbn)] filter all books with isbn number
$..book[?(#.price<10)] filter all books cheapier than 10
$..* All members of JSON structure.
You will have to loop through and find it.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
};
function getValueForFieldName(fieldName){
for(var i=0;i<json.fields.length;i++){
if(json.fields[i].fieldName == fieldName){
return json.fields[i].value;
}
}
return false;
}
console.log(getValueForFieldName("telNum"));
It might be a better option to modify the array into object with fieldName as keys once to avoid using .find over and over again.
fields = Object.assign({}, ...fields.map(field => {
const newField = {};
newField[field.fieldName] = field.value;
return newField;
}
It's not possible.. Native JavaScript has nothing similar to XPATH like in xml to iterate through JSON. You have to loop or use Array.prototype.find() as stated in comments.
It's experimental and supported only Chrome 45+, Safari 7.1+, FF 25+. No IE.
Example can be found here
Clean and easy way to just loop through array.
var json = {
"responseObject": {
"name": "ObjectName",
"fields": [
{
"fieldName": "refId",
"value": "2170gga35511"
},
{
"fieldName": "telNum",
"value": "4541885881"
}]
}
$(json.responseObject.fields).each(function (i, field) {
if (field.fieldName === "telNum") {
return field.value // break each
}
})

Autocomplete displays key and value using Alpaca forms

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.

Unwanted backslash in json when stored in localstorage

I am storing a json first in localstorage and then again storing it in final json but I am getting extra backslash in my final json. My code is:
<!DOCTYPE html>
<html>
<body>
<script>
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
]
localStorage.setItem("myData", JSON.stringify(mi))
var FinalJson = {
"Collected values" : localStorage.getItem("myData"),
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
</script>
</body>
</html>
Output I am getting is:
{"Collected values":"[{\"name\":\"Alex\",\"address\":\"abc\"} {\"name\":\"George\",\"address\":\"efg\"}]","Place":"washington"}
Where am i going wrong that I am getting this extra backslash. How can I remove the extra backslashes? P.S. I don't want to directly store the variable mi in my FinalJson, as it contains some more complicated values which I have removed here for simplicity.
It's stringified twice
var FinalJson = {
"Collected values" : JSON.parse(localStorage.getItem("myData")),
"Place" : "washington"
};
http://jsfiddle.net/Kh5Br/
var mi = [{
"name": "Alex",
"address": "abc"
},
{
"name": "George",
"address": "efg"
}
];
localStorage.setItem("myData", JSON.stringify(mi))
var tes = JSON.parse(localStorage.getItem("myData")); //It was "work". I thougt you missed that
var FinalJson = {
"Collected values" : tes,
"Place" : "washington"
};
document.write(JSON.stringify(FinalJson));
document.write(tes);

Categories

Resources