Autocomplete search box - javascript

I followed a video tutorial but I failed to output the result regardless many hours works. The output I expect is when user type some name to search for a company for example, companies' name will be show as a suggestion list. After select a certain company, more details of the company will be shown such as location, opening hours. I attach my HTML, JavaSCript and example JSON file here.
<body>
<div id="searcharea">
<label for="search">Ajax search</label>
<p> enter the name </p>
<input type="search" name="search" id="search" placeholder="company
name" />
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="script.js"></script>
</body>
</html>
$(#search).keyup(function() {
var searchFiled = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('mylist.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
if (val.user.search(myExp) != -1) {
output += '<li>';
output += '<h2>' + val.company + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('$update').html(output);
});
});
{
"data": [{
"user_id": "1",
"name": "Lala",
"address": "somewhere on the world",
"company": "big company",
}, {
"user_id": "2",
"name": "Tom",
"address": "USA",
"company": "CocaCola",
}]
"reminds": 0,
"message": "this is a message",
"myID": 0
}

Related

Display json data in html table using jQuery

How to display json data in html table using jQuery ? and How can i remove case sensitive while searching the result?
expected output
How can i display the result in my table? How can i achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (
data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
console.log(output);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
You need to create a table and need to append coming data to this table using below code:-
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
To do case-insensitive comparison use .toUpperCase()
Working snippet:-
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for (i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].toUpperCase().indexOf(skills.toUpperCase()) !== -1) || (data[i]["email"].toUpperCase() === email.toUpperCase()) || (
data[i]["username"].toUpperCase() === username.toUpperCase())) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
var output = getResult();
var html = '';
$.each(output,function(key,value){
html +='<tr>';
html +='<td>'+ value.username + '</td>';
html +='<td>'+ value.email + '</td>';
html +='<td>'+ value.skills + '</td>';
html +='</tr>';
});
$('table tbody').html(html);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<br>
<table>
<thead>
<tr>
<th>Username</th>
<th>Email ID</th>
<th>Core Skills</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
You can use Data-table jQuery plugin to generate table from jsondirectly like
$('#tableId').DataTable({
data: jsonData,
columns: [
{ data: 'username',title:'Username'},
{ data: 'emailId',title:'EmailId'},
{ data: 'skils',title:'Core Skills'}
],
"search": {
"caseInsensitive": false
}
});
For More detail follow Data-table jQuery Plugin.
Here is the code
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
];
function BindDataToTable(d,obj){
var keys=Object.keys(d[0]);
var table=document.createElement("table");
var trHead=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var th=document.createElement("th");
th.innerHTML=item;
trHead.appendChild(th)
})
table.appendChild(trHead)
for(var i=0;i<d.length;i++){
var tr=document.createElement("tr");
jQuery(keys).each((index,item)=>{
var td=document.createElement("td");
td.innerHTML=d[i][item];
tr.appendChild(td)
})
table.appendChild(tr)
}
jQuery(obj).append(table);
}
BindDataToTable(data,"#tableElement")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
<div id="tableElement">
</div>

How to display the JSON data in a table depending on search?

I'm trying to display the data in the table depending on search. How can I achieve this?
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}
]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" value="submit">
Expected o/p:
search any field ex:
input: java,
output :john and jane profiles
input:sql
output: only jane profile //he is the person who has sql skill
if nothing matches show 0 results
User can search using any one field, if any one item matches that profile should be displayed in my table. How can I do this? Can anyone please help me sort it out?
/* Dataset*/
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
/* Get Result */
function getResult() {
/* Read value from input fields */
var skills = $("#skills").val() || '',
email = $("#email").val() || '',
username = $("#username").val() || '';
var result = [],
i;
for(i = 0; i < data.length; i++) {
if ((skills !== '' && data[i]["skills"].indexOf(skills) !== -1) || (data[i]["email"] === email) || (data[i]["username"] === username)) {
result.push(data[i]);
}
}
return result;
};
$('#submit').click(function onClick() {
console.log(getResult()); // print expected data
});
<script
src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input id="skills" type="text" placeholder="skills">
<input id="email" type="email" placeholder="mail id">
<input id="username" type="text" placeholder="username">
<input id="submit" type="submit" value="submit">
in ES6 you can do it :
results = array.filter (x=>x.username.search(search_txt));
let my_list = [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"},{"username":"Chuck Berry","email":"cb#gmail.com","skills":"vuejs"}];
results = my_list.filter (x => x.skills.search('java')!=-1);
console.log(results);
//result is : [{"username":"John Doe","email":"jn#gmail.com","skills":"java,c,html,css"},{"username":"Jane Smith","email":"js#gmail.com","skills":"java,sql"}]
<!DOCTYPE html>
<html>
<head>
<title>SEARCH</title>
</head>
<body>
<input type="text" placeholder="skills" id="skills">
<input type="email" placeholder="mail id" id="email">
<input type="text" placeholder="username" id="username">
<input type="submit" value="submit" id="submit">
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Skills</th>
</tr>
<tr id="search">
</tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
$('#submit').click(function(){
var skills = $('#skills').val();
var email = $('#email').val();
var username = $('#username').val();
if(username){
search(username);
}
});
function search(username){
var name = username;
var html ;
data.forEach(function(currentValue, index, array){
if(currentValue.username == name){
html = "<td>"+currentValue.username+"</td>"+
"<td>"+currentValue.email+"</td"+
"<td>"+currentValue.skills+"</td>"
;
}else{
html = "Result Not Found";
}
});
return $('#search').html(html);
}
</script>
</body>
</html>
You can make a search function for skills like this:
var data = [{
"username": "John Doe",
"email": "jn#gmail.com",
"skills": "java,c,html,css"
},
{
"username": "Jane Smith",
"email": "js#gmail.com",
"skills": "java,sql"
},
{
"username": "Chuck Berry",
"email": "cb#gmail.com",
"skills": "vuejs"
}];
var skills = "java,c";
function search(){
result = [];
var setSkills = skills.split(","); console.log(setSkills);
data.map((current,index)=>{
let currentSkills = current.skills.split(","); //console.log(currentSkills);
// currentSkills = ["java", "c", "html", "css"]
// setSkills = ["java", "c"] ;
// length of set currentSkills == length of set (currentSkills + setSkill) --> mean setSkills is subset of currentSkills
let bool = Array.from(new Set(currentSkills) ).length == Array.from(new Set(currentSkills.concat(setSkills)) ).length;
if(bool)
console.log(data[index]);
});
}
<input type="text" placeholder="skills">
<input type="email" placeholder="mail id">
<input type="text" placeholder="username">
<input type="submit" onclick="search();" value="submit">

Removing the Item from the dropdown once its added using angular

HTML Code
<!doctype html>
<html ng-app="plunker">
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="style.css">
<script>
document.write("<base href=\"" + document.location + "\" />");
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="MainCtrl">
<h1> NG options</h1>
<form name="addUser">
Application:
<select ng-model="filterAddUser.application" ng-init ="filterAddUser.application = 'STACK'" title="" ng-options="value as value for (key , value) in applicationStatus">
</select>
Roles:
<select ng-model="filterAddUser.role" title="" ng-init ="filterAddUser.role = 'R'" ng-options="role.value as role.param for role in roleStatus">
</select>
<button ng-click="addToCart()">AddItem</button>
<div class="addCart">
<ul ng-repeat="item in items">
<li><b>Application:</b> {{item.application}}</li>
<li><b>Role:</b> {{item.role}}</li>
<li class="actionOptions">
<button ng-click="toggleSelected($index)">removeItem</button>
</li>
</ul>
</div>
</form>
</body>
</html>
Javascript Code
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.addToCart = function() {
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = "";
$scope.filterAddUser['role'] = "";
}
$scope.toggleSelected = function(index) {
$scope.items.splice(index, 1);
};
});
All that i am trying to do is when i add the application to the cart that application needs to be removed from the dropdwon and also when i click on the remove item that needs to be pushed back to the cart i have included a plunker as well http://plnkr.co/edit/kSsetX?p=preview
need help on the same.
Updated your plunkr: http://plnkr.co/edit/QQobh7Jx76r7lDzw7TzV
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [];
var deletedApplication = [];
$scope.applicationStatus = {
"TEST App": "TEST",
"ABC App": "ABC",
"TRY App": "TRY",
"SIR App": "SIR",
"LOPR App": "LOPR",
"STACK App": "STACK"
};
$scope.roleStatus = [{
"param": "Read",
"value": "R"
}, {
"param": "Write",
"value": "W"
}, {
"param": "Admin",
"value": "A"
}, {
"param": "Super Approver",
"value": "SA"
}, {
"param": "Supervisor",
"value": "S"
}];
$scope.filterAddUser = {
application: $scope.applicationStatus[0],
role: $scope.roleStatus[0]
};
$scope.addToCart = function() {
deletedApplication.push([
$scope.filterAddUser.application, $scope.applicationStatus[$scope.filterAddUser.application]
]);
delete $scope.applicationStatus[$scope.filterAddUser.application];
$scope.items.push({
application: $scope.filterAddUser.application,
role: $scope.filterAddUser.role
});
// Clear input fields after push
$scope.filterAddUser['application'] = $scope.applicationStatus[0];
$scope.filterAddUser['role'] = $scope.roleStatus[0];
}
$scope.toggleSelected = function(index) {
var addApp = deletedApplication.filter(function(deletedApp){
return deletedApp[0] === $scope.items[index].application;
})[0];
$scope.applicationStatus[addApp[0]] = addApp[1];
console.log($scope.applicationStatus);
$scope.items.splice(index, 1);
};
});

Output object array loop in javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have the following code. I'm trying to output each key value ("company" and "address") the different "city1, 2 ,3" object (list goes on and on in the real example). in to a <p> using javascript. I am feeling a bit lost since I've tried a lot of different ways but I can't get it to work. I believe it might be due to the structure. If it would only be one city there would be no problem.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
"city2":
[
{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}
],
"city3":
[
{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
},
{
"company": "Microsoft",
"address": "Husvägen 38"
}
]
};
You can iterate the data object using for...in and then iterate the array inside with forEach.
var body = '';
for(var city in data) {
data[city].forEach(function(entry) {
body += '<p>' + entry.company + ', ' + entry.address + '</p>';
});
}
console.log(body);
If it's reasonable within your product requirements, you might consider using list elements rather than a simple <p>. Try to use the appropriate document.createElement methods rather than building a string. Something like:
var data = {
"city1": [{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
}, {
"company": "Hemköp",
"address": "Allegatan 26"
}],
"city2": [{
"company": "Ica Nära",
"address": "Centrumvägen 7"
}],
"city3": [{
"company": "Hora brothers kiosk",
"address": "Rövsgatan 43"
}, {
"company": "Microsoft",
"address": "Husvägen 38"
}]
};
var cityList = document.getElementById("city-list");
for (var cityName in data) {
if (data.hasOwnProperty(cityName)) {
var city = document.createElement("li");
var cityLabel = document.createElement("p");
cityLabel.textContent = cityName;
city.appendChild(cityLabel);
var companyList = document.createElement("ul");
city.appendChild(companyList);
var companies = data[cityName];
for (var i = 0; i < companies.length; ++i) {
var company = document.createElement("li");
company.textContent = companies[i].company + ": " + companies[i].address;
companyList.appendChild(company);
}
cityList.appendChild(city);
}
}
<ol id="city-list"></ol>
Similar to Ben's answer. I personally like plain for..in loops over foreaches in javascript, but its a preference.
var data = {
"city1":
[
{
"company": "Ica kvantum",
"address": "Orrgatan 3-5"
},
{
"company": "Hemköp",
"address": "Allegatan 26"
}
],
...
};
var html = "";
for(var city in data)
{
//you can append the city to the html here if you want
// html += "<h2>" + city + "</h2>";
for(var company in data[city])
{
for(var field in data[city][company])
{
html += "<p>" + field + ": " + data[city][company][field] + "</p>";
}
}
}

Multilevel list menu with JSON and jQuery Mobile

I try to reach following structure
a list of (distinct!) categories
Category 1
Category 2
Category n
And each Category links to the posts within the Category. And the posts link to the content
Post 1 Cat 1 --> Content Post 1 Cat 1
Post 2 Cat 2 --> Content Post 2 Cat 1
Question: I don't know how to create the distinct list of categories which leads to the posts. Any solutions?
This is my JSON example (this is from the json api plugin in wordpress)
{"status": "ok",
"count": 10,
"count_total": 20,
"pages": 2,
"posts": [
{
"id": 86,
"type": "post",
"slug": "inaktiviert",
"url": "http://localhost/wordpress/?p=86",
"status": "publish",
"title": "Post 1 Cat1",
"content": "his is content for Post1 Cat 1.",
"date": "2014-03-04 15:09:51",
"modified": "2014-03-04 15:09:51",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 84,
"type": "post",
"slug": "kann-nicht-aktualisiert-werden",
"url": "http://localhost/wordpress/?p=84",
"status": "publish",
"title": "Post 2 Cat1",
"content": "<p>This is content for Post2 Cat 1.</p>\n",
"date": "2014-03-04 15:09:25",
"modified": "2014-03-04 15:09:25",
"categories": [
{
"id": 1,
"title": "Category 1",
"description": "",
"parent": 0,
"post_count": 4
}
],
},
{
"id": 74,
"type": "post",
"slug": "dieses-symbol-zeigt-an",
"url": "http://localhost/wordpress/?p=74",
"status": "publish",
"title": "Post 1 Cat2",
"content": "This is Content for Post1 Cat 2",
"date": "2014-03-04 15:06:47",
"modified": "2014-03-04 15:06:47",
"categories": [
{
"id": 2,
"title": "Category 2",
"description": "",
"parent": 0,
"post_count": 3
}
],
}
]}
And this my JS
$(document).on("pagecreate", "#page1", function(){
var liste = $('#liste');
var AllListItems = '';
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
AllListItems += '<li>' + postTitle + '</li>';
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.empty().append(AllListItems).listview("refresh");
$("body").append(AllDynamicPages);
});
DEMO
I would approach it this way: Instead of a list, create a collapsible set where each child collapsible is a category, and each category collapsible contains a list of posts.
Here is your updated FIDDLE
So the top level HTML markup would be a collapsible set:
<div id="thelist" data-role="collapsibleset" data-theme="a" data-content-theme="a">
</div>
Then the code:
var liste = $('#thelist');
var AllDynamicPages = '';
$.each(daten.posts, function(index1, data) {
var postid = data.id;
var postTitle = data.title;
var postContent = data.content;
for (var i = 0; i< data.categories.length; i++) {
var catid = data.categories[i].id;
var catTitle = data.categories[i].title;
//see if we already have this category, if not create new collapsible
var $cat = $("#cat" + catid);
if ($cat.length == 0){
$cat = $('<div id="cat' + catid + '" data-role="collapsible"><h3>' + catTitle + '</h3><ul data-role="listview"></ul></div>');
liste.append($cat);
}
//create post link in category collapsible list
var postlink = '<li>' + postTitle + '</li>';
$cat.find("ul").append(postlink);
AllDynamicPages += '<div data-role="page" data-add-back-btn="true" id="page' + postid + '"><div data-role="header"><h1>' + postTitle + '</h1></div><div data-role="content">' + postContent + '</div></div>'
}
});
liste.enhanceWithin();
$("body").append(AllDynamicPages);
It is the same iteration as you had before, but now for each category, we check if there is already a collapsible for that category. If there is not we create one and add it to the set. Then we create a link for the post and add it the list widget within the category collapsible.
Finally we call .enhanceWithin() to apply jQM styling.
The dynamic pages part stays exactly the same.

Categories

Resources