vendredi 4 septembre 2020

How Do I Randomly Pull Some Multiple Data from external JSON files and Display them in a page?

could I please have some help

I am trying to achieve a situation that when the JSON data is loaded in, only a randomised set amount of the data will be pulled from the data source and displayed, for instance 10, 20 or 30 etc without any duplication, instead of what is currently occurring where the entire data is being loaded in.

Also, at the moment I have over 20 separate JSON files with differing amount of data ranging from about 10 to over 350 in some cases.

You will note from my JScript code that only one of the JSON file will load once the page has loaded. Whenever I require any of the other JSON data files to be loaded in, I have to resort to changing the file name at the myQuizUrl from ‘tricky|_streets.json’ to ‘schools.json’ etc for instance.

 I am sure there is a way to create a button that when clicked, it will move on to another page and load the other JSON data in another page, or replace the current data with a new set in current page. Both solutions are desired if possible, as I could then decide which one to go with at a later date.



Ideally, I would also like to add a candidate’s name such as ‘John Doe’ where the progress and scores will be tracked and stored and can be retrieved later. However, I appreciate this will likely prove difficult and taxing.



I’ve provided some code snippets and would be grateful for any help provided, even partially.

I’m relatively new to all things JScript, but has got this far with help of others. I find myself on a very steep learning curve.



Thanks in advanced.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title></title>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <header>
        <h1>City Council</h1>
        <h2>Location Knowledge Mock Test:</h2>
        <h3><span class='quiz-title'>Quiz Title</span></h3>

        <div id="stats-div">
            <div id="result">Score = <span id="selected"></span></div>  <div id="notchecked">Remaing Questions or Not Answered = <span id="unselected"></span></div> 
    <!-- Counting only worked after JS code was moved from the 'head' tag to the bottom of the body tag -->
    <div id="totalquestions">Total Amount Of Questions = <span id="num-of-questions"></span></div> <!-- ids swapped around -->
    <div><strong>Score Percentage</strong> <span id="score-perc" style="color: green; font-size: 1.5em;"></span> <strong>%</strong></div>
    <div id="perScoreDiv">
    </div>

 <input type="button" id="tick-all-btn" onclick="checkAll2()" class="btn btn-link" value="Tick All Answers">
 <input type="button" onclick="uncheckAll2()" class="btn btn-link" value="Reset Test">
</div>
</header>

<div id="wrapper">
<div id="q-wrapper">

<form>
</form>

</div>


</div>
  <script src="script.js"> </script>
  </body>
</html>   
const buildQuestion = function(title, category, {name, value}){
  return document.createRange().createContextualFragment(`<label class='q-texts'><input type='checkbox' class='check2 ${category}' name='${title}' value='${value}'/> ${name}</label>`);
}
const buildCategory = function(title, category){
  const categoryEl = document.createElement("formset");
  const legendEl = document.createElement("legend");
  legendEl.textContent = category;
  categoryEl.appendChild(legendEl);
  return categoryEl;
}

const buildQuiz = function(JSONUrl){
  /***
   * the JSONurl parameter is the url of the file
   *  containing the entirety of the quiz data.
   */
  const quizEl = document.querySelector("form");
  const headerEl = document.querySelector("header");
  const titleEl = headerEl.querySelector(".quiz-title");

  fetch(JSONUrl)
    .then(response => response.json() )
    .then(quizObject =>{
      titleEl.textContent = quizObject.title;
      quizObject.categories.forEach(function({category, questions}){
        const categoryEl = buildCategory(quizObject.title, category);
        questions.forEach( function(question){
          const questionEl = buildQuestion(quizObject.title, category, question);
          categoryEl.appendChild(questionEl);
        })
        quizEl.appendChild(categoryEl);
      })
      document.querySelector("#num-of-questions").textContent = quizEl.querySelectorAll("input[type='checkbox']").length;
// Count Unticked boxes
quizEl.addEventListener("change", ()=>{
    const uncheckedEls = quizEl.querySelectorAll("input[type='checkbox']:not(:checked)").length;
    document.querySelector("#unselected").textContent = uncheckedEls;

    // Counts ticked boxes
    const checkedEls = quizEl.querySelectorAll("input[type='checkbox']:checked").length; // Added in by me
    document.querySelector("#selected").textContent = checkedEls; // Added in by me

    // Score percentage
    const totalEls = Number(document.querySelector("#num-of-questions").textContent);
    document.querySelector("#score-perc").textContent = Number(((totalEls-uncheckedEls)/totalEls )*100).toFixed(2);
})      
    })
}

/***
 * Here is where we actually call the quiz building
 *  parts. This gets the JSON data, and builds the form
 *  dynamically. Change this to:
 *  "./JSON/schools.json",
 *  "./JSON/dental-surgeries.json" or
 *  "./JSON/veterinarians.json"
 *  to view the same quiz template with different data.
 */
let myQuizParam = window.location.search.toString().match(/(\?quiz=)([a-z0-9\-]*)/i );
let myQuizUrl = "";
console.log(JSON.stringify(myQuizParam));
if (myQuizParam && myQuizParam.length > 0){
myQuizUrl = `./JSON/${myQuizParam[2]}.json`;
} else {
  myQuizUrl = `./JSON/tricky_streets.json`;
}

buildQuiz(myQuizUrl);

// Reset test and Check all checkboxes

//v2 Tick all Checkboxes
function checkAll2() {
  var inputs = document.querySelectorAll('.check2');
  for(var i = 0; i < inputs.length; i++) {
    inputs[i].checked = true;
    inputs[i].dispatchEvent(new Event("change", {bubbles: true}))
  }
}

// Untick All Checkboxes
function uncheckAll2() {
  var inputs = document.querySelectorAll('.check2');
  for(var i = 0; i < inputs.length; i++) {
    inputs[i].checked = false;
    inputs[i].dispatchEvent(new Event("change", {bubbles: true}))
  }
}   
{
  "title": "Tricky Streets Withinin City Boundries",
  "categories": [
    {
      "category": "Local",
      "questions": [
        
        {
          "name": "Chessman Court: Estcort Rd",
          "value": "TSWICB:TCBS01"
        },
        {
          "name": "Pegotty Bungalows: Stanway Rd",
          "value": "TSWICB:TCBS02"
        },
        {
          "name": "Mendip Cl: Chiltern Rd",
          "value": "TSWICB:TCBS03"
        },
        {
          "name": "Brecon Cl: Chiltern Rd",
          "value": "TSWICB:TCBS04"
        },
        {
          "name": "Quantock Rd: Fieldcourt Dr",
          "value": "TSWICB:TCBS05"
        },
        {
          "name": "Cheviout Cl: Quantock Rd",
          "value": "TSWICB:TCBS06"
        },
        {
          "name": "Graham Gdns: Estcort Rd",
          "value": "TSWICB:TCBS91"
        }    
      ]
    }
  ]
}   
{
  "title": "Schools",
  "categories": [
    {
      "category": "Infants",
      "questions": [
        {
          "name": "Churchdown Infant School: Station Rd (Churchdon)",
          "value": "CIS:SR"
        },
        {
          "name": "Longlevens Infant School: Paygrove Ln",
          "value": "LIS:PL"
        },
        {
          "name": "Tredworth Infant School: Victory Rd",
          "value": "TIS:VR"
        },
        {
          "name": "Dinglewell Infant  School: Dinglewell",
          "value": "DIS:DW"
        },
        {
          "name": "Innsworth Infant School: Luke Ln",
          "value": "IIS:LN"
        },
        {
          "name": "Churchdown Village Infant School: Station Rd (Churchdon)",
          "value": "CVS:SR"
        },
        {
          "name": "Churchdown Parton Manor Infant School: Craven Drive (Churchdown)",
          "value": "CPMI:CD"
        }
      ]
    }
  ]
}
{
  "title": "Pubs",
  "categories": [
    {
      "category": "Local",
      "questions": [
        {
          "name": "Brew House And Kitchen: Quays",
          "value": "BHK:QY"
        },
        {
          "name": "Dr Foster: Kimberley Warehouse (The Docks)",
          "value": "DFR:TD"
        },
         {
          "name": "The Lord High Constable: Llanthony Warehouse (Wetherspoon)",
          "value": "TLHC:LW"
        },
        {
          "name": "Wheatstone Inn: Centre Severn",
          "value": "WSI:CS"
        },
        {
          "name": "Tank: Llanthony Rd (Wetherspoon)",
          "value": "TNK:LR"
        },
         {
          "name": "The Old Crown: Westgate St",
          "value": "TOC:WS"
        },
        {
          "name": "Miller and Carter: Olympus Park",
          "value": "MAC:OP"
        }
      ]
    }
  ]
}   



Aucun commentaire:

Enregistrer un commentaire