I'm building a webpage where you'll be able to display random elements fetched from a JSON database. For example, we could have a "what should I cook" button where you're given a random dish every time you click it.
So far, I've managed to create a button that, when clicked, writes out one (1) field from the several ones I have in my JSON file.
I want to add more elements to the JSON.
Also I'm trying to accomplish one of two alternatives:
Get the fields from a random element in the JSON file. (this is preferred over the second alternative)
OR
Get the elements from the JSON file in a specific order. So you could get a field from the first element when you click the button the first time, then one field from the second element when you click it the second time and so on.
Right now nothing works if I add another element.
This is how my code looks like right now.
JSON:
{
"visible": "1",
"date": "2011-01-16 19:48:27",
"submitterid": "2541",
"rating": "3",
"dubious": "1",
"imdbid": "0268126",
"id": "1919",
"title": "Adaptation",
"year": "2002"
}
HTML:
<html>
<head>
<title>hi</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js.js"></script>
<script>
var bechdelApi = "js.js";
$(document).ready(function(){
$("button").click(function(){
$.getJSON(bechdelApi, function(data){
$.each(data, function(i, field){
if (i == "title") {
$("div").append(field + " ");
}
});
});
});
});
</script>
</head>
<body>
<button>give me a movie!</button>
<div></div>
</body>
If you use TaffyDB, you could do something like this:
<!DOCTYPE html>
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/taffydb/2.7.2/taffy-min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<button class="movie-button">give me a movie!</button>
<div class="movies-container"></div>
</body>
</html>
<script>
var movies = TAFFY();
$.getJSON("yourAPICall", function( data ) {
movies.insert(data);
});
$(".movie-button").click(function(){
//updating each element in the movies db with the 'order' field, which is initialized with a random value
movies().update(function(){
this.order = Math.floor(Math.random() * 100);
return this;
});
//ordering the movies collection by the field 'order' and fetching the first movie on the new ordering
var movie = movies().order("order").first();
//appending movie title to container div
$(".movies-container").html($("<div class='movie-container'></div>").append(movie.title));
});
</script>
EXAMPLE: http://jsfiddle.net/87u27swk/
Related
Description:
I took a spinning wheel code from Github and edited it and created 2 spinning wheels.
The thing is that when the wheel stops and chooses a number (or letter) it displays it as an alert // alert(value); //. I would like to know how to print the number under the wheel instead of showing it as an alert. I tried document.body.textContent += value; // but it
displays the result on another blank page instead. Here's the code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<script type="text/javascript" src="src/rouletteWheel.js"></script>
<script type="text/javascript">
$(function(thisis){
var itemsToShow = 100;
var wheel = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
var items = {};
for(var i=0; i < itemsToShow; i++){
items[i] = wheel[i]
}
$('#canvas').rouletteWheel({
items : items,
selected : function(key, value){
alert(value);
},
spinText : 'Ticket Number',
});
});
</script>
<title></title>
</head>
<body style="background-color:black;" ></body>
<canvas id="canvas" width="740" height="740"></canvas>
</body>
</html>
To print the number under the wheel you had to create an html element inside body tag of your web page, for example
<p id="show_alert_value_p"></p>
than in your Js code add this line instead of alert
$('#canvas').rouletteWheel({
items : items,
selected : function(key, value){
//alert(value);
//comment alert and add below line
$('#show_alert_value_p').html(value);
},
spinText : 'Ticket Number',
});
You need to specify or create a HTML element that will hold the value of said wheel.
Something along the lines of...
<div>
<h3> Results are: </h3>
<h3 id="result"></h3>
</div>
And instead of the alert function use something like.
$("#result").text(value)
Overall you should be more specific in you question description and making your script runnable in from of a snippet would help people find a answer for you.
So, I'm trying to create a TODO list but I'm having problems with "click" events once I dinamically load content.
What I want to achieve is that, once I click an element, send the "id" through $.post to a PHP file that deletes said row from my MySQL Database. And then, shows a new list without the deleted row.
Currently, I'm loading my "list.php" with $.get onto my "#todo-list" div. However, once I click, the info is sent, the row gets deleted, I get the new list without the deleted element. Every is ok at that point.
However, when I click an element of my new list, nothing happenns.
This is my Javascript File:
$(function() {
$.get("list.php", function(data){
$("#todo-list").html(data);
$("#todo").on("click", "li", function(){
let li = $(this);
let id = li.attr("id");
$.post("list.php", {id: id}, function(data){
$("#todo-list").html(data);
});
});
});
});
Here is my HTML page:
<html>
<head>
<title>My test app</title>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="./script.js"></script>
<style>
.todo-list li:hover {
text-decoration: line-through;
}
</style>
</head>
<body>
<h1>TODO: Just a list with stuff to do...</h1>
<div id="todo-list">
Loading content...
</div>
</body>
</html>
And this is my PHP file:
// code to connect to MySQL with PDO...
if ($_POST) {
// code to delete the id
}
$data = $pdo->prepare("SELECT * FROM todo");
$data->execute();
echo "<ul id='todo'>\n";
while ($row = $data->fetch()) {
echo "<li id='{$row['id']}'>{$row['todo']}</li>\n";
}
echo "</ul>\n";
As said, nothing happens after I get the new list with the deleted row.
I want my new list to be clickable, the same way the first list is... and of course, if I have 20 elements, I want to be able to click and delete them without reloading the page. Is it possible?
your click hanlder to delete row should be like this,you need to assign event handler again to newly added rows,
function delete_row(){
let li = $(this);
let id = li.attr("id");
$.post("list.php", {id: id}, function(data){
$("#todo-list").html(data);
//assigne the event handle again
$("#todo").on("click", "li",delete_row)
});
}
$(function() {
$.get("list.php", function(data){
$("#todo-list").html(data);
$("#todo").on("click", "li",delete_row)
});
});
How would I be able to pull the data from the JS script within my HTML? I am wanting to pull the "Title", "Description", and "Link" objects and display them within my HTML code.
Here is the code:
<div class="roadMap" id="roadMap"></div>
<script src="/siteassets/bootstrap3/js/jquery-1.8.3.min.js"></script>
<script src="/publiccdnlib/PnP-JS-Core/pnp.min.js"></script>
<script type="text/javascript" src="/publiccdnlib/es6-Promise/es6-promise.auto.js"></script>
<script type="text/javascript" src="/publiccdnlib/fetch/fetch.min.js"></script>
<script src="/publiccdnlib/slick/slick.min.js"></script>
<script src="/publiccdnlib/CommonJS/CommonJS.js"></script>
<script src="/publiccdnlib/knockout/knockout.js"></script>
<script src="/publiccdnlib/knockout/knockout.simpleGrid.3.0.js"></script>
<script src="/publiccdnlib/toastr/toastr.min.js"></script>
<script src="/publiccdnlib/dialog/open-sp-dialog.js"></script>
<!--END Scripts for O365-->
<script>
$pnp.setup({
baseUrl: "https://fh126cloud.sharepoint.com/TrainingResourceCenter/O365Training"
});
$pnp.sp.web.lists.getByTitle("O365RoadMap").items.get().then(function(z) {
console.log(z);
var result = z.results.map(a => ({
Title: `${a.Title}`,
Description: `${a.Description}`,
Link: `${a.Link}`
}))
console.log(result);
document.getElementById("roadMap").innerHTML = JSON.stringify(result, null, 2)
})
</script>
<html lang="en">
<body>
<div>
/* Code goes here */
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
I see you are using jQuery so I will answer relative to it.
Using jQuery you can put text wherever you want using the text method.
For example, if you want to put the Title data in your div you could do:
$("div").text(result.Title);
The code above will place result.Title in every div on the page (which you only have one of.).
There are so many jQuery methods you could use as-well, such as append, prepend, and html. Append will put the text after the existing content of an element. Prepend puts the text before existing content of an element. Html with replace the html inside of an element.
So if you wanted to construct the HTML elements then place them on the DOM (the web page) you could do:
$(document).ready(function(){
var head = '<h1>${result.Title}</h1>';
var desc = '<p>${result.Description}</p>';
var link = '<a src="${result.Link}">${result.Link}</a>';
$("div").html(head + desc + link);
});
To put your Title, Description, and Link on the DOM. Hope this help you, good luck!
I have multiple select2 drop-downs. Their value are loaded from their respective json files. The form is slow to load.
I want to combine their json files into one file. How do I change my javascript to read from one json file?
Is it possible to save drop-down values locally, so when the form is loaded the second time, it reads from the memory not read json files again.
function mySelect2(file,field) {
$.getJSON(file, function(obj) {
$.each(obj, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
mySelect2("../data/contactsourcesources.json",'#source_of_contact');
mySelect2("../data/levelofstudysources.json",'#degree');
//mySelect2("../data/institutionssources.json",'#uni');
//mySelect2("../data/countries.json",'#countryorigin');
mySelect2("../data/degreessources.json",'#course');
});
</script>
</head>
<body >
<section>
<label for="source_of_contact">
Contact Method:
<select class="source_of_contact" id="source_of_contact" name="source_of_contact">
</select>
</label>
<label for="degree" class="lbl-text">Degree Type:<span id="required">*</span>
<select class="degree" id="degree" name="degree">
</select>
</label>
</section>
</body>
</html>
Json file:
{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}
I want to change the Json and JavaScript to
{"source_of_contact":{"Caf\u00e9 Connect\n":"7e0a7146","Academic Advising Day\n":"academic_advising_day"}}
function mySelect2(file,field) {
$.getJSON(file, function(obj) {
// obj.field, how do I get value of field? I want to be like this
// obj.source_of_contact
$.each(obj.field, function(key, value) {
$(field).select2({
data: [
{
id: value,
text: key
}
]
});
});
});}
Don't use CDN, download and use the local copy of the js . That will increase the time a bit,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
second in order to make it load the data faster don't call the all GetJSOn function at document ready, call each function one after another on change of the dropdown values.
I have included a file named test.php in the file index.php
lets assume index.php is like this
<html>
<head>
</head>
<body>
<h1 id="dash">Index</h1>
<div id='tab.php'>
<?php include('tab.php'); ?>
</div>
</body>
</html>
and tab.php is like this
<html>
<head>
</head>
<body>
<ul>
<li id='date' onClick="change_head(this.id);">Dates</li>
<li id='appoint' onClick="change_head(this.id);">Appointments</li>
<ul>
</body>
</html>
Here what i would like to do is, if the list item date is clicked(list items are actually tabs). The inner html of the h1 tag with id dash should be changed to Dates and if the list item appoint is clicked the inner html of same h1 tag with id dash should change to appointments.
how can i do that ?? i tried the usual javascript way by taking the ids and applying the if condition to change the innerHTML but it was not working..anyone pls help me how to do it
JAVASCRIPT (this is the js i tried to achive it...i added this in index.php)
function change_head(id){
dash = document.getElementById('dash').innerHTML;
if(id == date){
dash = "Date";
}
else if(id == appoint){
dash = "Appointment";
}
else{
dash = "Index";
}
}
You could try using jquery... something like this:
<script type="text/javascript">
$(document).ready(function () {
$("li#date").click(function () {
$("h1#dash").val("Dates");
});
$("li#appoint").click(function () {
$("h1#dash").val("Appointments");
});
});
</script>
Of course, if you had more of these tabs, I would create a single click event handler for all "li" elements and switch on the ID :-)
Assuming you're new to jquery, you'd also have to include the jquery script in your page. Something like:
<script src="/Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
Check out jquery.com to get started.
If you want do it with JavaScript (i.e. without page reloading), so you need use DOM innerHTML.
Something like (if you didn't use jQuery), didn't test this code through, hope you get idea:
var changetext = function(e,t) {
e.innerHTML = t;
},
elemheader = document.getElementById('dash'),
elemdate = document.getElementById('date'),
elemappoint = document.getElementById('appoint');
if (elemdate.addEventListener) {
elemdate.addEventListener('click',changetext(elemheader,'Date'),false);
}
if (elemappoint.addEventListener) {
elemappoint.addEventListener('click',changetext(elemheader,'Appoint'),false);
}