How handle $.getJSON file with strings and integer? - javascript

how can I parse Integer from the JSON file?
Or what is the problem below?
$('#search').keyup(function(){
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('data.json', function(data){
if(searchField === '') {
$('#update').html('');
return;}
var output ='<ul class="searchresults">';
$.each(data, function(key, val){
if(val.number.search(myExp) != -1) {
output += '<li>';
output += '<p>' + val.number + '</p>';
output += '<p>' + val.name + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
});
What is missing?
Error is:
Uncaught TypeError: val.number.search is not a function
Many thanks in advance!
Br

Probably it's a number, numbers don't have a search method. You could use .toString().search(...) to convert it to a string first.

Related

Alphabetize javascript for loop

I'm getting desired results, but need to order them alphabetically. I am unsure what to put in exactly in the code:
function showClients(data) {
var html = '';
for (var clientId in data) {
html += '<p>' + clientId;
html += data[clientId].connected ? ' connected' : ' disconnected';
html += '</p>';
}
if (!html) {
html += '<p>No clients connected</p>';
}
$('#connected_clients').html(html);
}
If I've got the layout of the data structure right, it is a key/value object, which in turn contains objects that have information such as connected.
In that case you can use Object.keys to get the keys first, sort those Object.keys(data).sort(), and create the html from there. For example:
function showClients(data) {
var html = Object.keys(data).sort().reduce(function(h, clientId){
return h + '<p>' + clientId
+ (data[clientId].connected ? ' connected' : ' disconnected')
+ '</p>';
}, '')
|| '<p>No clients connected</p>';
$('#connected_clients').html(html);
}
function showClients(data) {
var html = Object.keys(data).sort().reduce(function(h, clientId){
return h + '<p>' + clientId
+ (data[clientId].connected ? ' connected' : ' disconnected')
+ '</p>';
}, '')
|| '<p>No clients connected</p>';
$('#connected_clients').html(html);
}
showClients({Client3:{connected:true},Client1:{connected:true},Client2:{connected:false}});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=connected_clients></div>
Call sort on the data like Array.prototype.sort(data). If you don't pass a compare function, it will sort the elements alphabetically.
function showClients(data) {
var html = '';
for (var clientId in Array.prototype.sort.call(data)) {
html += '<p>' + clientId;
html += data[clientId].connected ? ' connected' : ' disconnected';
html += '</p>';
}
if (!html) {
html += '<p>No clients connected</p>';
}
$('#connected_clients').html(html);
}

How to clear results from json file using JQuery and Javascript?

I am trying to get data from JSON and present it with my 'Search' function, after I display the data I want to clear the result until the user will enter new word.
Now it is displaying my all JSON file without clearing it.
The code looks like that:
<body>
<br>
<div id="searcharea">
<h2>Search Word</h2>
<input type="search" id="search"/>
</div>
<div id="update">
</div>
<script type="text/javascript" src='//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type="text/javascript">
$('#search').keyup(function() { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
$.getJSON('index.json', function(data){ //get the json file
var output = "<ul id='result'>";
$.each(data, function(key, val){
if(val.name.search(myExp) != -1){ //search for the data in the json file
output += '<li>';
output += '<h3>' +val.name+ '</h3>';
output += '<h3>' +val.song+ '</h3>';
output += '<h3>' +val.part+ '</h3>';
output += '</li>';
}
});//end each
output += "</ul>";
$('#update').html(output); //output result to the update div
});
});
</script>
</body>
The JSON file looks like that:
[
{
"name":"Word: 'asked' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1"
},
{
"name":"Word: 'a' ",
"song":"Name of the song: 'Drive My Car' ",
"part":"Part: 1, 2, 3"
}
]
Please try this.Further more, I recommand you to use .trim function.
$('#search').keyup(function () { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm.trim()!= '') {
$.getJSON('index.json', function (data) { //get the json file
$.each(data, function (key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
});
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
Here is a working solution
Another way is to use this code:
if(searchTerm!="")
$('#update').html(output); //output result to the update div
else
$('#update').html('');
$('#search').keyup(function () { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm != "") {
$.getJSON('index.json', function (data) { //get the json file
$.each(data, function (key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
});
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
Example:
var data = [{
"name": "Word: 'asked' ",
"song": "Name of the song: 'Drive My Car' ",
"part": "Part: 1"
}, {
"name": "Word: 'a' ",
"song": "Name of the song: 'Drive My Car' ",
"part": "Part: 1, 2, 3"
}];
$('#search').keyup(function() { //when key is pressed in search bar
var searchTerm = $(this).val(); //val of search bar
var myExp = new RegExp(searchTerm, "i"); //regular experation
var output = "<ul id='result'>";
if (searchTerm != "") {
$.each(data, function(key, val) {
if (val.name.search(myExp) != -1) { //search for the data in the json file
output += '<li>';
output += '<h3>' + val.name + '</h3>';
output += '<h3>' + val.song + '</h3>';
output += '<h3>' + val.part + '</h3>';
output += '</li>';
}
}); //end each
}
output += "</ul>";
$('#update').html(output); //output result to the update div
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="searcharea">
<h2>Search Word</h2>
<input type="search" id="search" />
</div>
<div id="update">
</div>

loop from json files and search then get the value via jquery and json

I have a bit of a question. which is a loop.
I have a simple looping which when I clicked some numbers and it will search and loop through out my json file.
here is my code
function showSortedRoute(){
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult");
var result = "";
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == getRuoute) {
var image = val.image;
var structure_name = val.name;
var copy = val.copy;
var address = val.address;
var access = val.access;
var type = val.type;
var getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});
}
this does not give me any results, saying no area ID found, but in
alert("no area id found" + getRoute);
and the alert shows displays like four times.
I can check that the value is the same.
code for matching up with integers with json is not working.
There's a few errors in your code:
getRuoute in this line: if(val.area_id == getRuoute){ seems to be
undeclared variable
name in this line: result += '<h4>' + name + '</h4>'; is also
undeclared
getRoute in this line: alert("No area ID Found" + getRoute);
seems to be undeclared variable
Here is corrected and optimized version:
$.getJSON('my.json', function(data) {
var $resultHTML = $("#divResult"),
result = '<ul class = "list clearfix">';
$.each(data, function (key, val){
if (val.area_id == 'getRuoute') { // check type and name of 'getRuote', maybe 'getRoute'?
var image = val.image,
structure_name = val.name,
copy = val.copy,
address = val.address,
access = val.access,
type = val.type,
getarea = val.area;
result += '<div class="iconArea">';
result += '<h4>' + structure_name + '</h4>';
result += '<h4><b>' + getarea + '</b></h4>';
result += '</div>';
result += '<p class="catch">' + copy + '</p>';
result += '<dl class="detailArea clearfix">';
result += '<dd>' + address + '</dd>';
result += '<dd>' + access + '</dd>';
result += '</dl>';
result += "</ul>";
$resultHTML.html(result);
} else {
alert("No area ID Found" + getRoute);
}
});
});

Reading Json Data in Javascript / php (Format issue)

I have this code which reads the json data below (This code works well):
var data = [{"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end":"2011-10-29T14:15:00.000+10:00", "title":"Meeting"}];
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.title + '</li>';
});
Ive now changed the data (see below) and for some reason it's not working
var data = {"users":[{"firstname":"peter","lastname":"tosh"},{"firstname":"mike","lastname":"Marsh"}]}
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
I know the data format is slightly different ... I'm I forgetting something?
$.each(data.users, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
try this
Although your code is in javascript and not PHP. The problem is that you're having an array inside of an array. So on the first loop your only getting users and not firstName or something like that. Fix:
var data = {"users":
[
{"firstname":"peter","lastname":"tosh"},
{"firstname":"mike","lastname":"Marsh"}
]
}
var output = '';
$.each(data, function(i, users){
$.each(users, function(index, value) {
output += '<li>' + value.firstname + '</li>';
});
});

Target Specific Javascript Object Literal fields and array with jquery

I cant seem to get this to work. Im trying to do two things
A). Get the following code to show up correctly. The first element is show 'undefined
<ul>
<li>Button
<ul>
<li>x:1</li>
<li>y:2</li>
<li>width:3</li>
<li>height:4</li>
</ul>
</ul>
Here is my code:
$(document).ready(function() {
var data = {
"Controls": [{
"Button":[{ "x": "1","y": "2","width": "3","height": "4" }],
"Image":[{"x": "5","y": "6","width": "7","height": "8"}],
"TextField":[{"x": "9","y": "10","width": "11","height": "12"}]
}]
}
var str = '<ul>';
$.each(data.Controls, function(k, v) {
str += '<li>' + k[0] + '</li><ul>';
for(var kk in v.Button[0]){
str += '<li>' + kk + ':' + v.Button[0][kk] + '</li>';
}
str += '</ul>';
});
str += '</ul>';
$('div').append(str);
})
And
B). trying to display a list(separate list from above) of just the fields. like this:
<li>Button</li>
<li>Image</li>
<li>TextField</li>
I think that the answer to the second lies in the first, but I cannot seem to get the targeting right.
Any help is appreciated
Demo
To get the first list:
var str = '<ul>';
var target = "Button";
str += '<li>' + target + '<ul>';
$.each(data.Controls[0][target][0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
str += '</ul>';
To get the second list:
var str = '<ul>';
$.each(data.Controls[0], function(k,v) {
str += '<li>' + k + '</li>';
});
str += '</ul>';
To target them by index, so Button is 0:
var str = '<ul>';
var target = 0;
var count = 0;
$.each(data.Controls[0], function(k,v) {
if(count == target)
{
str += '<li>' + k + '<ul>';
$.each(v[0], function(kk, vv){
str += '<li>' + kk + ':' + vv + '</li>';
});
str += '</ul></li>';
return false; // <-- break because we got what we wanted
}
count++;
});
str += '</ul>';
First of all, this has nothing to do with JSON. JSON is a string-serialization format. What you have here is an object literal.
Second, I have no idea why you are wrapping all your object definitions inside Controls, with arrays, seems like a lot of extra hassle. You are also doing things in a very non-jQuery way.
You could try something like this:
var data = {
"Controls": {
"Button":{ "x": "1","y": "2","width": "3","height": "4" },
"Image":{"x": "5","y": "6","width": "7","height": "8"},
"TextField":{"x": "9","y": "10","width": "11","height": "12"}
}
}
$('div').append('<ul id="outer_ul">');
$.each(data.Controls, function(key, value) {
$('#outer_ul').append('<li>' + key + '</li>', '<ul id="' + key +'">');
$('#field_list').append('<li>' + key + '</li>');
$.each(value, function(key2, value2) {
$('#' + key).append('<li>' + key2 + ':' + value2 + '</li>');
}
}
This code populates both you div as well as a ul with the id of field_list which would represent the container into which you want to put the second list (so adjust this code according the the proper jQuery selector you want to use.

Categories

Resources