Autocomplete with JSON - javascript

I have JSON data and I guess my JSON is works but there is something that I didn't understand how it's going to work ? when I wrote cities or countries nothing happend how will I make it work ?
I havedata-list attribute and when I clicked my input my data-list opening automatically it's ok so far.but if I wrote something my inline data-list attribute musn't work anymore only my Json must work how can I do that ?
I'm using Awesomplete plugin and if you want to see my project on codepen please click to see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = "Cities : " + myObj.cities;
document.getElementById("demo1").innerHTML = "countries : " + myObj.countries;
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
} else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
} else {
comboplete.close();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.css" rel="stylesheet" />
<div id="demo"></div>
<div id="demo1"></div>
<!--<input type="text" class="awesomplete" data-list="PHP,ASP,ASP.NET,Python,CSS,HTML,C#,C++,Delphi,Visual Basic" onclick="showlist()">-->
<br><br> with auto list
<input id="test" data-list="CSS, JavaScript, HTML, SVG, ARIA, MathML" class="dropdown-input" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>

You have to access the attribute "data-list" of your input and set your json as data source.
Try this:
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)

Related

How can I control my Json with jquery?

I have JSON data and I have two array with cities and countries.When I clicked my input cities are opening automatically but I want to do this too:
if I cliked my input cities must open (this is okey I did it)
but at the same time if I wrote something for example denmark (this is the list of countries) than denmark must seen if is matching.. how can I do that ?
click to see if you see on codepen
var myJSON = '{ "cities":[ "copenhagen", "london", "hamburg" ], "countries":[ "denmark", "norway", "sweden" ] }';
var myObj = JSON.parse(myJSON);
var testInput = document.getElementById("test");
testInput.setAttribute("data-list", myObj.countries)
function showlist() {
}
var comboplete = new Awesomplete('input.dropdown-input', {
minChars: 0,
});
Awesomplete.$('#test').addEventListener("click", function() {
if (comboplete.ul.childNodes.length === 0) {
comboplete.minChars = 0;
comboplete.evaluate();
}
else if (comboplete.ul.hasAttribute('hidden')) {
comboplete.open();
}
else {
comboplete.close();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/awesomplete/1.1.1/awesomplete.min.js"></script>
<input id="test" class="dropdown-input" />
What I get from your question is that you want entries from both arrays to show when you type anything. To achieve that use (myObj.cities.concat(myObj.countries)) array instead of myObj.cities or myObj.countries array alone.

Get data from JSON based upon the input received

I need to fetch data based upon the input received.
For example, if the input is 'Royal python', I should get details of Royal python.but with the following code, i get error saying 'The file you asked for does not exist'. But I get the value into fname. But not sure if the function is correct to fetch data from from array.Also I wanted to know if there is any shorter way to do this. Please help?
I'm using JavaScript for this, my code and the web page look are below:
<!DOCTYPE html>
<html>
<body>
<form> <input type="text" name="fname" required>
<button onclick="myFunction()">OK</button> `enter code here`
</form>
<p id="demo"></p>
<script> var text = '{"animals":[' +
'{"Common Name":"Royal Python","Order":"Squamata","Family":"Boidae","Genus":"Python","Species":"regius","Zoo":"Blackpool Zoo","Number":4 },' +
'{"Common Name":"Emperor Penguin","Order":"Sphenisciformes","Family":"Spheniscidae","Genus":"Aptenodytes","Species":"forsteri",` "Zoo":"Welsh Mountain Zoo","Number":35 },' +`
'{"Common Name":"Chimpanzee","Order":"Primates","Family":"Pongidae","Genus":"Pan","Species":"troglodytes", "Zoo":"Blackpool Zoo","Number":8 }]}';
obj = JSON.parse(text);
//function to fetch data based on input
function myFunction(fname)
{ var ani = "";
if (document.getElementByname("fname")="Royal Python")
var ani = document.getElementById("demo").innerHTML = obj.animals[0].Zoo + " " + obj.animals[0].Species; }} </body> </html>
Here is a solution to your problem that uses a for loop to check each index of the animal array for a match. This match will be case-insensitive also.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<input type="text" name="fname" required>
<button onclick="fetchAnimal()">OK</button> `enter code here`
<script>
var animalsArr = [{
"commonName": "Royal Python",
"order": "Squamata",
"family": "Boidae",
"genus": "Python",
"species": "regius",
"zoo": "Blackpool Zoo",
"number": 4
}, {
"commonName": "Emperor Penguin",
"order": "Sphenisciformes",
"family": "Spheniscidae",
"genus": "Aptenodytes",
"species": "forsteri",
"zoo": "Welsh Mountain Zoo",
"number": 35
}, {
"commonName": "Chimpanzee",
"order": "Primates",
"family": "Pongidae",
"genus": "Pan",
"species": "troglodytes",
"zoo": "Blackpool Zoo",
"number": 8
}]
function fetchAnimal() {
var i;
var len = animalsArr.length;
// convert input name to lower-case
var name = document.getElementsByName('fname')[0].value.toLowerCase();
for (i = 0; i < len; i++) {
// check to see if lower-case input is the same as lower-case animal name (this ensures the match is case-insensitive)
if (animalsArr[i].commonName.toLowerCase() === name) {
document.getElementById('demo').innerHTML = animalsArr[i].zoo + ' ' + animalsArr[i].species;
}
}
}
</script>
</body>
</html>
Note: It is highly recommended move the JS code into an external script file if you intend to add more interactivity to the page.
There are a number of issues in your code:
document.getElementByname("fname")="Royal Python" should be document.getElementsByName("fname")[0].value == "Royal Python"
Also, it's cumbersome to write the text string and then parse it as JSON. Just use a JavaScript object.
You're also making it difficult on yourself when trying to determine the animal. Use Array.findIndex() if your browser supports it.
Here's a working example:
var obj = {animals:[{CommonName:"Royal Python",Order:"Squamata",Family:"Boidae",Genus:"Python",Species:"regius",Zoo:"Blackpool Zoo",Number:4 }, {CommonName:"Emperor Penguin",Order:"Sphenisciformes",Family:"Spheniscidae",Genus:"Aptenodytes",Species:"forsteri",Zoo:"Welsh Mountain Zoo",Number:35 }, {CommonName:"Chimpanzee",Order:"Primates",Family:"Pongidae",Genus:"Pan",Species:"troglodytes", Zoo:"Blackpool Zoo",Number:8 }]};
//function to fetch data based on input
function myFunction() {
var name = document.getElementsByName("fname")[0].value;
var index = obj.animals.findIndex(function(item) {
return item.CommonName === name;
});
if (index >= 0) {
document.getElementById("demo").innerHTML = obj.animals[index].Zoo + " " + obj.animals[index].Species;
}
}
<input type="text" name="fname" required value="Royal Python">
<button onclick="myFunction()">OK</button>
<p id="demo"></p>

Find an element in a JSON file and show it in HTML

I have the following JSON file
{
"agenti":[
{"codice":"3425", "nome":"fabrizio", "cognome":"mazzeini", "azienda":"kra", "indirizzo": {"via":"via milano", "citta":"Roma","stato":"Italia"}},
{"codice":"3476", "nome":"marco", "cognome":"sormani", "azienda":"bertucci", "indirizzo": {"via":"via Siena", "citta":"Milano" , "stato":"Italia"}},
{"codice":"4525", "nome":"francesco", "cognome":"stefanucci", "azienda":"ovs", "indirizzo": {"via":"via italia", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3405", "nome":"emilio", "cognome":"emiglietti", "azienda":"paoletti", "indirizzo": {"via":"via delle forze armate", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3915", "nome":"gianni", "cognome":"sperti", "azienda":"giacomazzi", "indirizzo": {"via":"via quarenghi", "citta":"Milano" , "stato":"Italia"}},
{"codice":"3429", "nome":"franca", "cognome":"solari", "azienda":"apple", "indirizzo": {"via":"via dei missaglia", "citta":"Milano" , "stato":"Italia"}}
]}
And the following HTML/JS file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<h1>JSON</h1>
<button id="es" type="button" onclick="testJSON()"> UPLOAD JSON </button>
Search for agenti per <br> <br>
Nome<input type="text" id="nome"> <br><br>
<button type="button" id="filtra" onclick="filter()"> Filter </button>
<p id="demo"> </p>
<script>
var agenti = "";
function testJSON()
{
var successo = function(result) {
console.log("success");
console.log(result);
agenti = result;
};
var error = function (error) {
console.log(error);
};
$.ajax ({
dataType: "json",
url: "agenti.json",
success: successo,
error: error
});
var a = 10;
}
</script>
<script>
function filter() {
var name = document.getElementById("nome").value;
for (var i=0; i < agenti.length; i++) {
if (agenti[i].nome === nome) {
document.getElementById("demo").innerHTML = name;
}
}
}
</script>
</body>
</html>
I fill the input box with "fabrizio" for example... But HTML does not return any value and does not print "fabrizio" as a found element in the JSON file...
But if i do something like that:
<script>
var name = document.getElementById("nome").value;
document.getElementById("demo").innerHTML = name;
function filter() {
for (var i=0; i < agenti.length; i++) {
if (agenti[i].nome === nome) {
}
}
}
</script>
and i fill in the input box with a casual name, HTML returns the name in the document (and prints it) even if is not present in the JSON file
I guess the problem is in the for loop and precisely in the if conditional
What can i do ? Thanks to everybody
you have :
agenti = result;
so within that data structure you must go to :
agenti.agenti[0].nome
to get your result. agenti is set to the entire encapsulating object and you want the first object, agenti, within that. I would obviously change your variable to something less confusing.
You made two mistakes there. First of all mixing up JSON object keys with Javascript variables which apparently led to confusion. Also, like Mark pointed out, you have wrapped the result in the variable agenti. I made a JSFiddle where all things are working. If you have more questions feel free to comment. What you do is basically:
var name = document.getElementById("nome").value;
for (var i = 0; i < agenti.agenti.length; i++) {
if (agenti.agenti[i].nome === name) {
document.getElementById("demo").innerHTML = agenti.agenti[i].nome + ' & ' + agenti.agenti[i].codice;
}
}
OLD ANSWER
The variable "nome" is not declared, "name" is.
if (agenti[i].nome === name) {}
"nome" is a typo you made in the JSON file and the HTML DOM, I guess. You should correct that.
Also, you don't have to create two script tags for two functions. Just put both of them into the first script tag.

passing a variable to .html() function

<!-- The select drop down menu (works fine) -->
<select id="select-event-type">
<?php foreach ($this->events as $event) {
echo "<option value='" .$event->event_id. "'>" .$event->event_title."</option>";
}?>
</select>
<!-- The javascript, which is supposed to output something according to the chosen option in the select drop down -->
<script>
(function ($) {
var events = <?php echo (count($this->events) > 0) ? json_encode($this->events) : "null"; ?>;
$(document).ready(function() {
$('#select-event-type').change(function() {
if (events) {
var event = events[this.selectedIndex];
$('#event-details').html(event);
}
});
});
})($);
</script>
<!-- In this div the output will be displayed -->
<div id="event-details"></div>
The event variable undefined.
If I for example do this: var event = 'hello' It does output 'hello' as it is supposed to.
So the problem seems to be with this part: events[this.selectedIndex];. What did I do wrong?
I am really new to this. Thank you so much for your help!!
UPDATE:
Console output (in chrome):
<script>
(function ($) {
var events = JSON.parse({"1":{"event_id":"1","event_title":"event1","event_desc":"event1","event_location":"eventlocation","event_requirements":"event1","event_date":"2022-07-20 15:00:00"},"2":{"event_id":"2","event_title":"event2","event_desc":"event2","event_location":"eventlocation","event_requirements":"event2","event_date":"2015-04-20 15:00:00"},"3":{"event_id":"3","event_title":"event3","event_desc":"event3","event_location":"eventlocation","event_requirements":"event3","event_date":"2019-11-20 16:00:00"}}); $(document).ready(function() {
$('#select-event-type').change(function() {
if (events) {
var event = events[$(this).selectedIndex];
$('#event-details').html(event);
}
});
});
</script>
JSON:
{
"1": {
"event_id": "1",
"event_title": "event1",
"event_desc": "event1",
"event_location": "eventlocation",
"event_requirements": "event1",
"event_date": "2022-07-20 15:00:00"
},
"2": {
"event_id": "2",
"event_title": "event2",
"event_desc": "event2",
"event_location": "eventlocation",
"event_requirements": "event2",
"event_date": "2015-04-20 15:00:00"
},
"3": {
"event_id": "3",
"event_title": "event3",
"event_desc": "event3",
"event_location": "eventlocation",
"event_requirements": "event3",
"event_date": "2019-11-20 16:00:00"
}
}
To get the value of the select element use this.value. Thus change:
var event = events[this.selectedIndex];
To:
var event = events[this.value];
However, if you json is an array with indices 0,1,2,3,4 rather than an object with option values as keys then your use of this.selectedIndex is correct.
UPDATE:
In the light of the sample JSON posted the correct code should be:
var event = events[this.selectedIndex + 1].event_title;
Special Note
You can get all the event data by using either:
var event = JSON.stringify( events[this.selectedIndex + 1] ); //gives you a string of everything
Or you could construct how you want it to look like so:
var event = $('<div/>');
$.each( events[this.selectedIndex + 1], function(k,v) {
event.append( $('<div/>',{text:k + ': ' + v}) );
});
See this answer for the jQuery way of accessing the selectedIndex property. Your answer might look like:
var event = events[$(this).prop("selectedIndex")];
Firstly you dont need the 2 ready instances. Try to do it, if dont work please tell me.
<script>
$(document).ready(function() {
var events = <?php echo (count($this->events) > 0) ? json_encode($this->events) : "null"; ?>;
$('#select-event-type').change(function() {
if (events) {
var event = events[$(this).selectedIndex];
$('#event-details').html(event);
}
});
});
</script>
and what means the selectedIndex ?

Why "Microsoft JScript runtime error: Object expected"?

I'm about 1 day old in using jquery, and is currently having a nightmare with it. I alreadt spent half of my day trying to get rid of this error.
I did some reading after “googling” the error (sorry, Bing!) and discovered that most of these errors result from the jquery file not being properly loaded. Okay…that started to point me in the right direction but I still couldn’t figure out why it wasn’t pathing properly. I mean, I was doing as people said – I would drag the .js file into my designer and it would print out the proper path, but still the error shows.
Here's my exact code in my editor template (with the error):
#model bool
#{
string status = "Active";
string buttonValue = "Deactivate";
string hiddenValue = "true";
if (!ViewData.Model)
{
status = "Inactive";
buttonValue = "Activate";
hiddenValue = "false";
}
}
<div style="width:100px; float:left;">
<img id = "AD_Img" src = "/Content/themes/base/images/icon_#(status).png" alt = #(status) />
<label for = "AD_Img" id = "AD_Label" >#(status)</label>
</div>
<div style="width:100px; float:left;">
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
<input id = "AcntStatus" type = "hidden" name = "AcntStatus" value = #(hiddenValue) />
</div>
and in the same cshtml file, the script goes this way:
<script type="text/javascript" src="/Scripts/jquery-1.5.1.min.js">
function ChangeStatus()
{
var ButtonVal = $("#AD_Button").val();
alert(ButtonVal);
if (ButtonVal == "Deactivate")
{
var stat = "Inactive";
var buttonVal = "Activate";
var HiddenValue = "false";
}
else if (ButtonVal == "Activate")
{
stat = "Active";
buttonVal = "Deactivate";
HiddenValue = "true";
}
$("#AD_Img").attr({src: "/Content/themes/base/images/icon_"+stat+".png", alt: stat});
$("#AD_Label").html(stat);
$("#AD_Button").val(buttonVal);
$("#AcntStatus").val(HiddenValue);
}
</script>
The debugger stops on the ChangeStatus function of the input element on the following line:
<input type="button" id = "AD_Button" value = #(buttonValue) style = "width:100px" onclick = "ChangeStatus()" />
i tried to debug it by using this in my function code:
function ChangeStatus()
{
var ButtonVal = document.getElementById("AD_Button").value;
alert(ButtonVal);
}
And it works properly, it returns the exact string that I'm looking for without that error, but why? What's wrong with my codes?
Please help me figure this out.
This:
$("#AD_Img").attr(src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat);
forces an Syntax-error. It has to be:
$("#AD_Img").attr({src: "../../../Content/themes/base/images/icon_"+stat+".png", alt: stat});
Edit:
Also take a look at your <script>, you can't mix external JS and internal JS.
This:
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js">
//your code
</script>
Has to be splitted into
<script type="text/javascript" src="../../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
//your code
</script>

Categories