I want to make a live search and then select those suggestions for further implementation!But it doesn't put values in the select field.In other words,option tag is not working!!!
here is the code!!!
//index.php
<html lang="en"><head>
<meta charset="utf-8">
<title>Live Search</title>
</head>
<body>
<div id="searcharea">
<label for="search">live search</label>
<p>Enter the name</p>
<input type="search" name="search" id="search" placeholder="name or info">
</div>
<div>
<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>
</div>
<script src="jquery-1.12.2.min.js"></script>
<script src="basic.js"></script>
</body>
</html>
//location.json
[
{
"name":"Barot Bellingham",
},
{
"name":"Jonathan G. Ferrar II",
},
{
"name":"Hillary Hewitt Goldwynn-Post",
},
{
"name":"Hassum Harrod",
},
{
"name":"Jennifer Jerome",
},
{
"name":"LaVonne L. LaRue",
},
{
"name":"Constance Olivia Smith",
},
{
"name":"Riley Rudolph Rewington",
},
{
"name":"Xhou Ta",
}
]
//basic.js
$('#search').keyup(function()
{
var searchField=$('#search').val();
var myExp=new RegExp(searchField,"i");
var slct_start='<select>';
$('#top').html(slct_start);
$.getJSON('location.json',function(data)
{
var output='<ul class="searchresults">';
$.each(data,function(key,val){
if(val.name.search(myExp)!=-1)
{
output='<option '+'value='+val.name+'>'+val.name+'</option>';
}
});
$('#center').html(output);
});//get json
var slct_end='</select>';
$('#bottom').html(slct_end);
});
Instead of this KeyUp function,
You can use the Jquery AutoComplete functionality for easy search.
Try that one.
Refer this AutoComplete search in Jquery
I found that your location.json's data is not standard, it should like this:
[
{
"name":"Barot Bellingham"
},
{
"name":"Jonathan G. Ferrar II"
},
{
"name":"Hillary Hewitt Goldwynn-Post"
},
{
"name":"Hassum Harrod"
},
{
"name":"Jennifer Jerome"
},
{
"name":"LaVonne L. LaRue"
},
{
"name":"Constance Olivia Smith"
},
{
"name":"Riley Rudolph Rewington"
},
{
"name":"Xhou Ta"
}
]
first we put a html file as index.html
<div class="container">
<h4 class="publish-work" >PUBLISHED WORKS AVAILABLE</h4>
<br>
<input type="search" class="search" name="search" >
<br>
<br>
<table id="datalist" class="table table-bordered" style="height: 400px; overflow-y: auto;">
<thead>
<th>S.no</th>
<th>Name</th>
<th>Price</th>
</thead>
<tbody>
</tbody>
</table>
then add a script.js file
$(document).ready(function()
{
var table_object = [];
for(var i=0; i<1500; i++)
{
var object1 = [''];
object1[0] = randomString() ;
object1[1] = i+1;
object1[2] = i*10/2;
table_object.push( object1 );
}
console.log( table_object );
function render ( arraylist ) {
var html = '';
for(var i=0;i<arraylist.length;i++)
{
//var html = '';
html += '<tr>';
html += '<td>'+arraylist[i][0]+'</td>';
html += '<td>'+arraylist[i][1]+'</td>';
html += '<td>'+arraylist[i][2]+'</td>';
html += '</tr>';
//html1 += html;
//console.log(html);
}
console.log(html);
$("#datalist tbody").html(html);
}
render( table_object );
$(".search").on("keyup", function() {
var value = $(this).val();
var anotherval = [''];
var dummyarray = [];
for ( i=0; i<table_object.length; i++ )
{
if ( table_object[i]["name"].indexOf(value) != -1 )
{
dummyarray.push(table_object[i]);
}
}
render(dummyarray);
});
function randomString ()
{
var randomStringArray = [];
var stringSet = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 100; i++) {
var maxLength = Math.floor(Math.random() * (10 - 5 + 1)) + 5;
var String = "";
for (var j = 0; j < maxLength; j++) {
String += stringSet[Math.floor(Math.random() * stringSet.length)];
}
randomStringArray.push(String);
}
return String;
}
});
thats it..
Related
Good morning, I tried to push a temporaly value to a JSON file with the comand "MyJSON.name.push" but it tells me: "Undefined its not an object". I tried some forms and with javascript arrays worked but I need to do it on external JSON file. The error only appears if I click some button. Someone can help me?
Thanks you.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) MyJSON.push('{name:"url",url:"url1"}')
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.name.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.urls.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.SSL= SSL;
}
JSON FILE(json.json):
var MyJSON = [{
name:"Google",
url: 'google.es',
},
{
name:"Yahoo",
url: 'yahoo.com',
}
]
Change your this.Add() function like this:
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.push({"name":url,"url":url1})
el.value = '';
this.FetchAll();
}
}
I'm trying to pick a value from JSON and insert it on a diferents text boxes but it show the value "undefined". The objective is insert link on name space and link space and save it on LocalStorage and some statick values like google and yahoo. Please can someone help me? Thanks you so much.
EDIT: Now is solved, and now dont work the buttons, some one? Please
NEW PROBLEM:The error only appear if I press the buttons (it don't create the buttons).
ERROR: Can't find variable SSL
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = ss =function() {
var data= '';
if (MyJSON.length > 0) {
for (i = 0; i < MyJSON.length; i++) {
data += '<tr>';
data += '<td>' + MyJSON[i].name+ '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(MyJSON.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
MyJSON.name.push(url.trim());
el.value = '';
this.FetchAll();
}
if (url) {
MyJSON.url.push(url1.trim());
el1.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = MyJSON.name[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.urls.splice(item, 1, url.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
MyJSON.name.splice(item, 1);
this.FetchAll();
};
}
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
}
I'm practicing javascript and learning on my own. I am creating a game where you enter a text coordinates and the game tells you whether you dug something up or not. But I am trying to implement a text box so you can play out of a browser instead of the command prompt, but I'm having trouble getting the game to take the text and then run the code using it when you click on the button.
Here is the HTML for the game.
<head>
<meta charset="UTF-8">
<title>Game Board</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript" src="board.js"></script>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<center>
<h1>Archaeology Board</h1>
Palace = 5 Spaces </br>
Temple = 4 Spaces </br>
Forum = 4 Spaces </br>
House = 3 Spaces </br>
Hut = 2 Spaces </br>
<h3>
<table id="board">
</table>
</h3>
<p>
<label for="DigBox">Enter dig coordinates:</label>
<input type="text" id="DigBox" size="3" value="" />
<input type="button" value="Dig" id="run" />
</p>
<p><input type="button" value="Restart Game" id="restart" /></p>
</center>
</body>
</html>
This is the js file to create the board.
function GameBoard()
{
this.ruins = [
{
name: "Palace",
size: 5,
successes: 0
},
{
name: "Temple",
size: 4,
successes: 0
},
{
name: "Forum",
size: 4,
successes: 0
},
{
name: "House",
size: 3,
successes: 0
},
{
name: "Hut",
size: 2,
successes: 0
}
];
this.rows = ["a", "b", "c", "d", "e", "f", "g", "h"];
this.columns = ["1", "2", "3", "4", "5", "6", "7", "8"];
this.cellMarker = 'X';
}
GameBoard.prototype.setBoard = function ()
{
var i, j, boardTags;
boardTags = "";
// build the first row of column labels
boardTags += "<tr><th> </th>";
for (j = 0; j < this.columns.length; j++) {
boardTags += "<th>" + this.columns[j] + "</th>";
}
boardTags += "</tr>";
// build the table with HTML tags
for (i = 0; i < this.rows.length; i++) {
boardTags += "<tr>";
boardTags += "<th>" + this.rows[i] + "</th>"; // row labels
for (j = 0; j < this.columns.length; j++) {
boardTags += "<td class='square' id='cell" +
this.rows[i] + this.columns[j] + "'>" + this.cellMarker + "</ td>";
}
boardTags += "</tr>";
}
$("#board").html(boardTags);
for (i = 0; i < this.ruins.length; i++) {
this.setRuin(this.ruins[i]);
}
}
GameBoard.prototype.dig = function(square, processResult)
{
var target, targetObj;
target = $("#cell"+square).attr('ruin');
if (target) {
targetObj = this.getRuin(target);
if (! $("#cell"+square).attr('dug')) {
$("#cell"+square).attr('dug', 'yes');
targetObj.successes++;
}
return targetObj;
}
else {
return undefined;
}
}
GameBoard.prototype.getRuin = function(ruinName)
{
for (var i = 0; i < this.ruins.length; i++) {
if (ruinName === this.ruins[i].name) {
return this.ruins[i];
}
}
return undefined;
}
GameBoard.prototype.randomSquare = function()
{
var colIndex = Math.floor(Math.random() * this.columns.length);
var rowIndex = Math.floor(Math.random() * this.rows.length);
return this.rows[rowIndex] + this.columns[colIndex];
}
GameBoard.prototype.setRuin = function(ruin)
{
// keeps randomly trying to place a ruin until it fits on the board
var candidateSquare = this.randomSquare();
var across = Math.random() < 0.5;
var success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
while (! success) {
candidateSquare = this.randomSquare();
across = Math.random() < 0.5;
success = this.tryPlacement(ruin, candidateSquare, across, ruin.size);
}
}
GameBoard.prototype.tryPlacement = function(ruin, square, across, size) {
var nextSquare;
if (size === 0) {
// ruin fits!
return true;
}
else if (! square) {
// invalid square
return false;
}
if (! $("#cell" + square).attr('ruin')) {
$("#cell" + square).attr('ruin', ruin.name);
// see if the rest of the ruin fits
if (this.tryPlacement(ruin, this.increment(square, across), across, size - 1)) {
// ruin fits!
return true;
}
else {
// ruin didn't fit --- undo occupied square and return false
$("#cell" + square).removeAttr('ruin');
return false
}
}
}
GameBoard.prototype.increment = function(square, across)
{
if (across) {
// need to increment the column dimension if possible
var colIndex = this.columns.indexOf(square.charAt(1));
colIndex++;
if (colIndex === this.columns.length) {
return undefined;
}
else {
return square.charAt(0) + this.columns[colIndex];
}
}
else {
// need to increment the row dimension if possible
var rowIndex = this.rows.indexOf(square.charAt(0));
rowIndex++;
if (rowIndex === this.rows.length) {
return undefined;
}
else {
return this.rows[rowIndex] + square.charAt(1);
}
}
}
This is the code I'm trying to implement in
$(function () {
tryDig = function(targetCell)
{
var targetObj = board.dig(targetCell);
if (targetObj) {
alert('Success finding the ' + targetObj.name);
$("#cell"+targetCell).html('#');
$("#cell"+targetCell).css('color', 'blue');
}
else {
alert('Failure!');
$("#cell"+targetCell).html('*').css('color', 'red');
}
}
board = new GameBoard();
board.setBoard();
});
initialize = function() {
$("#run").click(tryDig);
}
initialize = function() {
$("#restart").click(GameBoard.prototype.setBoard);
}
$(initialize);
I want to make it so whatever is in the text box, the game uses that as the coordinates to dig up in the board.
I've created a JSON file to call out the name of a list of beers to display ABV and country but I am unable to display the results on the webpage. I was able to get the select tag to drop down the list, but when selecting a beer, it will only show the selected results as "undefined."
Here is the JS code I have so far...
var $select = $("#beerListing");
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data['beer'].length; i++)
$select.append('<option id="' + data["beer"][i]['id'] + '">' + data["beer"][i]["beer_name"] + '</option>');
for (x in data) {
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
}
showBeerList();
});
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
} else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
HTML:
<html>
<head></head>
<body>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
JSON List called data.json
{
"beer": [{
"beer_name": "Organic Devon Cider",
"brewery_name": "Luscombe Organic Drinks",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "The Anchor & Hope",
"venue_city": "London",
"venue_state": "Greater London",
"brewery_country": "England"
}, {
"beer_name": "Beer A",
"brewery_name": "Beer A",
"beer_type": "Cider",
"beer_abv": "4.9",
"beer_ibu": "0",
"comment": "",
"venue_name": "Beer",
"venue_city": "New York",
"venue_state": "New York",
"brewery_country": "USA"
}]
}
You seemed to be adding the options to the select element twice and using for-in which iterates properties, not entries in an array.
Below snippet will not work as requires external data source.
var $select = $("#beerListing") ;
var beer = Array();
var country = Array();
$.getJSON("data.json", function(data) {
$select.html('');
for (var i = 0; i < data.beer.length; i = i + 1) {
if (beer.indexOf(data.beer[i].beer_name) < 0) {
beer.push(data.beer[i].beer_name);
country.push(data.beer[i].brewery_country);
}
}
showBeerList();
}
function showBeerList() {
var select = document.getElementById('beerListing');
for (var i = 0; i < beer.length; i++) {
var obj = document.createElement("option");
obj.text = beer[i];
obj.value = i;
select.appendChild(obj);
}
}
function getBeerInfo(picked) {
if (picked == "Pick Your Poison...") {
location.reload();
}
else {
document.getElementById("name").innerHTML = beer[picked];
document.getElementById("country").innerHTML = country[picked];
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>LCBO API TESTING</h1>
<select name="beerlist" id="beerListing" class="form-control" onchange="getBeerInfo(this.value)">
</select>
<br>
<label>Name:</label>
<label id="name">--</label>
<br>
<label>Country:</label>
<label id="country">--</label>
<br>
I got it working here: https://jsfiddle.net/bu7pkb5f/1/
What are you doing with:
if (beer.indexOf(data[x].beer_name) < 0) {
var y = beer.length;
beer[y] = data[x].beer_name;
country[y] = data[x].brewery_country;
}
I don't understand it but it's creating a third item in the list after the two real beer entries are processed. I left it commented out in the fiddle so you can check it out for yourself.
My submit button is finally working. However, it is not counting all of the votes in the results. How do I get my submit button to sort all of the votes?
HTML:
<!DOCTYPE html>
<html>
<link rel="stylesheet" text="text/css" href="movies.css">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<title>
Movie List
</title>
</head>
<body>
<h1>My Favorite Movies</h1>
<div id = "first">
<input type="text" id="movie" placeholder="Movie">
<button id="enter">Enter</button>
</div>
<div id="left">
<div id="list"><u>Chosen Films:</u></div>
<!-- <div>Chosen Films: <span id="list"></span></div> -->
<!-- <div id="films"></div> -->
<div id="best"><u>You're Best Films:</u></div>
<button id="submit">Submit</button>
</div>
<div id= "results"><u>Results</u></div>
<script type="text/javascript" src="movies.js"></script>
</body>
</html>
Javascript:
$(document).ready(function() {
var films = [];
// with working vote button
$("#enter").click(function () {
var movie = $("#movie").val();
var $btn = $('<button />', {
id: "vote",
type: "button",
text: "Vote",
value: movie,
click: function(){
var vote = this.value;
$("#best").append('<p>'+vote+'</p>');
films.push(vote);
}
});
var $p = $('<p />');
$p.append($btn, " ", movie);
$p.appendTo("#list");
});
});
So here is where the trouble is:
This code should allow the submit button to take the listed films under "your best films" and arrange them in a third list under "results" in order of their votes.
$("#submit").click(function () {
var ballot = {};
for (var i = 1; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var i = 0; i < elect.length; i++){
console.log(elect[i].key);
$("#results").append('<p>' + elect[i].key + '</p>');
}
});
Any suggestions or ideas would be appreciated!
$("#submit").click(function () {
var ballot = {};
for ( var i = 0; i < films.length; i++) {
var key = films[i];
ballot[key] = (ballot[key] || 0) + 1;
}
var elect = [];
for (key in ballot) elect.push({key: key, freq: ballot[key]});
elect.sort(function(a,b){return b.freq - a.freq});
console.log(elect);
for (var j = 0; j < elect.length; j++){
console.log(elect[j].key);
$("#results").append('<p>' + elect[j].key + '</p>');
}