How do I pass this JSON data to an autocomplete - javascript

Special thanks to Raúl Monge for posting a fully working code for me.
My problem was getting JSON data from a file.json and using this data to autocomplete search on it with JavaScript. The code that finaly got it working for me is the following:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('json/telefoonnummers.json', function(json) {
$.each(json.personen.persoon,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.naam+" - "+value.telefoonnummer;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
This is the html:
<body>
<div id="content">
<input type="text" id="search" />
</div>
And this has to be included in the head:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
Thanks stackoverflow!

NEW EDIT CODE WORKING:
<script>
$(document).ready(function(){
var arrayAutocomplete = new Array();
$.getJSON('data.json', function(json) {
$.each(json.persons.person,function(index, value){
arrayAutocomplete[index] = new Array();
arrayAutocomplete[index]['label'] = value.name;
arrayAutocomplete[index]['value'] = value.phoneno;
});
$( "#search" ).autocomplete({source: arrayAutocomplete});
});
});
</script>
Add this in head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
This is the html
<body>
<div id="content">
<input type="text" id="search" />
</div>
</body>

why not use
var data = [
"Aragorn",
"Arwen",
....
];
since all of those data are labels?

There you go
A working example with the data structure you have.
Just initialize the autocomplete once the JSON is loaded & the data is formatted.
$( "#search" ).autocomplete({source: availableTags});

Your document ready is within your function.
Try to write your function outside of your document ready.
Then write your document ready to call your function.
Some something like this:
function loadJson() {
//alert("Whoohoo, you called the loadJson function!"); //uncomment for testing
var mycontainer = [];
$.getJSON( "data.json" , function(data) {
//alert(data) //uncomment for testing
$.each( data, function( key, val ) {
//alert("key: "+key+" | val: "+val); //uncomment for testing
array.push([key , val]);
});
});
return mycontainer;
}
$(document).ready(function(){
//alert("Boojah! jQuery library loaded!"); //uncomment for testing
var content = loadJson();
dosomethingwitharray(content);
});
Hope this helps!
Also make sure you have jQuery included in your head ( <head> </head> ):
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
And add your javascript at the end of your body ( <body> </body> ).
To test if jquery does it's job try this:
<html>
<head>
<title>getting started with jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
</head>
<body>
<h1>my page</h1>
<p>this paragraph contains some text.</p>
<!-- javascript at end -->
<script>
$(document).ready(function(){
//show a dialog, confirming when the document is loaded and jquery is used.
alert("boojah, jquery called the document ready function");
//do something with jquery, for example, modify the dom
$("p").append('<br /> i am able to modify the dom with the help of jquery and added this line, i am awesome.');
});
</script>
</body>
</html>
PS. Uncomment alerts for testing stuff, so you can test what happens. If you have space in your document i suggest using $.append to an div that log's all action's so you can see exactly what's going on because alert's in a loop like the .each are quite annoying! more about append: http://api.jquery.com/append/

Related

How to get data from jquery form builder if there are multiple form initialized on the same page

I have a code like this:
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
$(document.getElementsByClassName('build-wrap')).formBuilder();
});
</script>
</body>
</html>
If it was initialized by id, then I could have get data with something like this:
var fbEditor = document.getElementById('build-wrap');
var formBuilder = $(fbEditor).formBuilder();
document.getElementById('getJSON').addEventListener('click', function() {
alert(formBuilder.actions.getData('json'));
});
However, I am using classname to initialize form builder. Is there any way, when click on save, get the respective form-builder data? I am using https://formbuilder.online/
Here is jsfiddle: https://jsfiddle.net/xycvbj3r/3/
#PS: there could be numerous form builder inside php loop.
You can try this:
formBuilder.actions.getData('json');
Or:
formBuilder.actions.getData();
The live demo is here: http://jsfiddle.net/dreambold/q0tfp4yd/10/
I was facing the same issue too. This worked for me
var list = ['#ins1', '#ins2', '#ins3'];
var instances = [];
var init = function(i) {
if (i < list.length) {
var options = JSON.parse(JSON.stringify([]));
$(list[i]).formBuilder(options).promise.then(function(res){
console.log(res, i);
instances.push(res);
i++;
init(i);
});
} else {
return;
}
};
init(0);
And to get data, you can use instances[key].actions.getData()
I am not sure how you are planning to save this data, but to help with your problem of getting form data for a particular form you can use something like this
var formBuilder = $(document.getElementsByClassName('build-wrap')).first().data('formBuilder').actions.getData()
Or to use it over a jQuery Collection then
$(document.getElementsByClassName('build-wrap')).each(function () {
var formBuilder = $(this).data('formBuilder').actions.getData()
})
There is a callback mentioned in the documentation, onsave which runs on editor save. So, when clicking on any form builder's save button, the respected form's data can be received.
Here is the code-
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
var options = {
onSave: function(evt, formData) {
// This is the respected form's data
console.log('MY DATA_________', formData)
},
};
$(document.getElementsByClassName('build-wrap')).formBuilder(options);
});
</script>
</body>
</html>
Here is the fiddle (couldn't create a working snippet due to not working CDNs.
)- https://jsfiddle.net/nehasoni988/rpo1jnuk/1/#&togetherjs=Mka9TJ4cex

JSON not returning the actual data from the url

I am trying to build a basic covid19 website. the code I am using is only returning [object Object] in the actual data. What I am doing wrong here?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("https://api.covid19api.com/summary", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
That's because you're trying to append JavaScript object to DOM. Instead, see what data you're getting (as someone mentioned in comments, by console.log) then you can edit your append part accordingly.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("https://api.covid19api.com/summary", function(result){
$.each(result.Countries, function(i, field){
$("div").append("<span>"+JSON.stringify(field)+"</span></br>");
});
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
Here I have a sample answer which appends all list of country. Understand each and every line and function how it works. I have appended list of country, how to render the rest items that I leave it to you. Don't get discouraged or disappointed; learning to code is a journey, not destination.
Note:https://cors-anywhere.herokuapp.com/ is added if you are running it in your localhost to avoid CORS's problem. If you have hosted the page, you can remove it.
$(document).ready(function(){
$("button").on('click',function(){
$.getJSON("https://cors-anywhere.herokuapp.com/https://api.covid19api.com/summary", function(result){
var obj=result;
var json = JSON.stringify(obj);
var s = JSON.parse(json);
s.Countries.map(function(c){
$("#result").append("<span>"+c.Country+"</span></br>");
})
console.log(s.Countries[0].Country);
});
});
});

How to load different html files in QUnit?

I'm using QUnit for unit testing js and jquery.
My HTML looks like this:
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<script src="../lib/jquery.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.16.0.css" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<!--This is where I may have to add startPage.html--->
<script src="../login.js"></script>
<script src="../test/myTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>
Currently, I'm adding login.js as shown and I'm getting references correctly to objects defined in login.js.
However, functions in login.js contains references to some dom elements defined in startPage.html which is located elsewhere.
So, if I say $('#login-btn'), it is throwing an error. Is there any way to fix this?
Can I
(a) refer to startPage.html to my qunit page given above?
(b) refer to or load startPage.html in the file where I'm running tests (myTests.js):
QUnit.test( "a test", function( assert ) {
assert.equal( 1, "1", "String '1' and number 1 have the same value" );//works
assert.equal( login.abc, "abc", "Abc" );//works with attributes
assert.equal(($("#userid").val()),'', 'Userid field is present');//fails
assert.equal( login.ValidUserId(), true, "ValidUserId" );//fails with functions
});
Does QUnit provide any method to load Html/php files so they'll be defined prior to testing. Like 'fixtures' in jasmine?
EDIT: Please also tell what to do in case I have startPage.php
There are a couple of ways you can do this. The simplest is just to use the built-in QUnit "fixtures" element. In your QUnit HTML file, simply add any HTML you want in the div with the id of qunit-fixture. Any HTML you put in there will be reset to what it was on load before each test (automatically).
<html>
...
<body>
<div id='qunit'></div>
<div id='qunit-fixture'>
<!-- everything in here is reset before each test -->
<form>
<input id='userid' type='text'>
<input id='login-btn' type='submit'>
</form>
</div>
</body>
</html>
Note that the HTML in the fixture doesn't really have to match what you have in production, but obviously you can do that. Really, you should just be adding the minimal necessary HTML so that you can minimize any side effects on your tests.
The second option is to actually pull in the HTML from that login page and delay the start of the QUnit tests until the HTML loading is complete:
<html>
<head>
...
<script type="text/javascript" src="http://code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script>
// tell QUnit you're not ready to start right away...
QUnit.config.autostart = false;
$.ajax({
url: '/path/to/startPage.html',
dataType: 'html',
success: function(html) {
// find specific elements you want...
var elem = $(html).find(...);
$('#qunit-fixture').append(elem);
QUnit.start(); // ...tell QUnit you're ready to go
}
});
</script>
...
</head>
...
</html>
Another way to do this without using jquery is as follows
QUnit.config.autostart = false;
window.onload = function() {
var xhr = new XMLHttpRequest();
if (xhr) {
xhr.onloadend = function () {
if(xhr.status == 200) {
var txt = xhr.responseText;
var start = txt.indexOf('<body>')+6;
var end = txt.indexOf('</body>');;
var body_text = txt.substring(start, end);
var qunit_fixture_body = document.getElementById('qunit-fixture');
qunit_fixture_body.innerHTML = body_text;
}
QUnit.start();
}
xhr.open("GET", "index.html");
xhr.send();
} else {
QUnit.start(); //If getting the html file from server fails run tests and fail anyway
}
}

Obtain this.index(this) in jQuery plugin

How can I clicked on that I get a tag index
My Html Code
<html>
<head>
<title>nss plugin</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="nss.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<img src="../img/is1.jpg"/>
<img src="../img/is2.jpg"/>
<img src="../img/is3.jpg"/>
<img src="../img/is4.jpg"/>
</body>
</html>
2 . My jquery plugin code.
(function( $ ) {
$.fn.nss = function( ) {
var thisindx = this.index(this);
console.log(thisindx);
return this;
};
}( jQuery ))
3.my javascript code
$(function(){
$('a[rel="group"]').click(function(){
$('a[rel="group"]').nss();
})
});
Why thisindx value is equal to 0
How can a person get the actual value
Not sure why you need a plugin, you can just do :
$(function(){
$('a[rel="group"]').on('click', function(){
$('a[rel="group"]').index(this);
});
});
to get the current elements index withing the group.
EDIT:
inside a plugin you get the collection, and iterate over it with return this.each, so using each individual iteration and the collection, you can get the elements index in the set of elements in the selector like so:
$.fn.nss = function( ) {
var elems = this
return elems.each(function() {
// all plugin code for multiple elements should normally go in a loop
// like this one to perform the same actions on every element
var thisindx = elems.index(this);
console.log(thisindx);
});
};
Try like this
var thisindx = this.index();
Or from the click event you can directly get the index value like
$(function(){
$('a[rel="group"]').on('click',function(){
$('a[rel="group"]').index();
//Better use like
$(this).index(); //or this.index();
});
});

Trying to parse xml file for javascript quiz

I am trying to create a javascript quiz, that gets the questions from a xml file. At the moment I am only starting out trying to parse my xml file without any success. Can anyone point me to what I am doing wrong?
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<div class="spmArr">
</div>
<script type="text/javascript">
var quizXML = '<quiz><Sporsmal tekst="bla bla bla"/><alternativer><tekst>bla</tekst><tekst>bli</tekst><tekst correct="yes">ble</tekst></alternativer><Sporsmal tekst="More blah"/><alternativer><tekst>bla bla</tekst><tekst correct="yes">bli bli</tekst><tekst>ble ble</tekst></alternativer></quiz>'
var quizDOM = $.xmlDOM( quizXML );
quizDOM.find('quiz > Sporsmal').each(function() {
var sporsmalTekst = $(this).attr('tekst');
var qDiv = $("<div />")
.addClass("item")
.addClass("sporsmal")
.appendTo($(".spmArr"));
var sTekst = $("<h2/>")
.html(sporsmalTekst)
.appendTo(qDiv);
});
</script>
</body>
</html>
When I try this in my browser the classes and div are not being created. And the page is just blank. Am i doing something wrong when I intialize the xml?
edited to add prototype.js and close function
Looks like you're forgetting to close your .each call. append ); after the statement for sTekst and your call will parse correctly.

Categories