i have a quiz with radio buttons ,sow i have to save the answears on my local storge ,but im stuck i don t know what else to do,im learnig sow dont hate me pls,tnx
This is my code sow far
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i ) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html = "<div><h2>Question " (i 1) ": " questionItem.question "</h2></div>";
html = "<div>";
for (let i = 0; i < questionItem.options.length; i ) {
html = "<div >";
html = "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" key "_option\" value=\"" questionItem.options[i] "\">" questionItem.options[i] ;
html = "</div>";
}
quiz.innerHTML = html;
}
quiz.innerHTML = "<input type=\"submit\" value=\"submit\">";
function save() {
var g1 = document.querySelector('input[type="radio]');
g1 = (g1) ? g1.value : '';
localStorage.setItem("g1", g1);
}
});
CodePudding user response:
You can simplify your AJAX dialog by using fetch()
instead of new XMLHttpRequest();
. I straightened out a few things in your code (also see the initial remarks in @brianagulo's answer) and prepared a little set of sample data to demonstrate the whole functionality of the quiz. The jsonplaceholder.typicode.com
url only serves as a working json-server endpoint. The received data is actually ignored here.
In your "production version" you will need to un-comment the line:
localStorage.setItem("quiz",JSON.stringify(ans))
The checked answers where collected in an object doing
[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
This
- collects all checked radio button inputs with (
document.querySelectorAll('input[type=radio]:checked')
), - converts the collection of DOM elements into a proper array (with
[... ]
)and eventually reduce()
-s its elements into an object where the element names are the property names and the (input-)element values are the property values.
And also please note that you can only store strings in local storage. Therefore I converted the ans
object into a JSON string before using it in the .setItem()
method.
const Q = {
quiz: [{
question: "Where was the Boston tea party?",
options: ["New York", "Detroit", "Boston", "Reno"]
}, {
question: "Where would you find Venice Beach?",
options: ["Detroit", "Venice", "Paris", "Los Angeles"]
}, {
question: "Where would you find Queens?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where is Greenwich Village?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where would you find the Gateway Arch?",
options: ["St. Quentin", "St. Louis", "St. Anton", "San Francisco"]
}]
}, quiz = document.getElementById("quiz");
var url = "quiz.json";
// in your productive version: comment out the following line
url = "https://jsonplaceholder.typicode.com/users/7"; // functioning test URL for fetch
function save(ev) {
ev.preventDefault();
const ans=[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
// in Stackoverflow snippets you cannot use local storage, so here is console.log instead:
console.log(ans);
// in your productive version: un-comment the following line
// localStorage.setItem("quiz",JSON.stringify(ans))
}
fetch(url).then(r => r.json()).then(object => {
// remove the following line:
object = Q; // use the static quiz from defined in Q instead ...
let json = object
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i ) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html = "<div><h2>Question " (i 1) ": " questionItem.question "</h2></div>";
html = "<div>";
for (let i = 0; i < questionItem.options.length; i ) {
html = "<label>";
html = "<input type=\"radio\" id=\"q\" name=\"qzz" key "_option\" value=\"" questionItem.options[i] "\"> " questionItem.options[i];
html = "</label><br>";
}
quiz.innerHTML = html;
}
quiz.innerHTML = "<input type=\"submit\" value=\"submit\">";
quiz.onsubmit=save;
});
<form id="quiz"> </form>
CodePudding user response:
There is a typo on your save
function. You are missing a quote after radio:
var g1 = document.querySelector('input[type="radio"]');
Also, your question is confusing but if what you are trying to do is get whether the radio is checked or not you must access the checked property and save that to localStorage. And if you want to save the state for all of the buttons then you should use querySelectorAll
and save them that way instead. Example below of accessing a single input's checked value:
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
For saving them all
Lastly, it seems you are not actually calling the save()
function. If your intention is to have the radios checked state saved to localStorage on click you may want to add an event to the submit button. For example:
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i ) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html = "<div><h2>Question " (i 1) ": " questionItem.question "</h2></div>";
html = "<div>";
for (let i = 0; i < questionItem.options.length; i ) {
html = "<div >";
html = "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" key "_option\" value=\"" questionItem.options[i] "\">" questionItem.options[i] ;
html = "</div>";
}
quiz.innerHTML = html;
}
quiz.innerHTML = "<input type=\"submit\" value=\"submit\">";
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
let submitButton = document.querySelector('input[type="submit"]');
submitButton.onclick = (event) => {
/* this prevents page refresh and submission to the backend which is a form default */
event.preventDefault();
// then we call the save function here
save();
};
});
If this was helpful please consider selecting as the answer