Automize array object display from array database - javascript

I have an array containing 10 objects. Each contains a question string, a correctAnswer string, and an object with 4 answer strings:
const DB = [
{
question: "some question",
answers: ["a", "variety", "of", "choices"],
correctAnswer: "variety"
}, ...
I have a function which captures the user's answer via radio button input, and saves it in a variable:
function feedbackPage(){
$('.js-quizform-questions').on('click', '.js-button-next', function(event){
event.preventDefault()
let yourAnswer = getFeedback()
$('.js-feedback-page').show().html(evalCorrectAnswer(DB))
})
}
You see that evalCorrectAnswer reaches out to the above database for validation. At the moment i am only able to display and validate the hardcoded first answer, which is dynamically generated like this:
function generateQuestionElement(item) {
return `
<h2>${item[0].question}</h2>
<form id='form'>
<fieldset>
<div class='css-answers'>
<input id='answer1' type='radio' name='answer' required>
<label for='answer1'>${item[0].answers[0]}</label>
</div>
<div class='css-answers'>
<input id='answer2' type='radio' name='answer' required>
<label for='answer2'>${item[0].answers[1]}</label>
I need a way to automatically choose the first question, to include its answers and display it via generateQuestionItem. Then I need to take that question (& its answers) out of the pool and display the next question once i click on a Next button on the eval page. I have a hard time implementing this feature in an object-oriented way.
Codepen

Construct a variable of
let questionNumber = 0
Then update the following line inside renderQuestion:
<label for='answer1'>${DB[questionNumber].answers[0]}</label>
Later create a function that updates questionNumber at each appropriate point.

Related

How to set up a specific reject message for a HTML number input element?

I have a loop of html forms <input type="number">, which are basically simple algebra calculations for certain people to fill in. I set the correct answer by limiting both the max and min accepted number to the same number. However, in this way, if the participant gives a wrong answer, the reject message would be something like this: "values must be greater than or equal to ...". It is technically correct but I would like it to only say "incorrect answer, please try again".
Is there any way to do this?
Tried to use something like alert =, but it doesn't meet my requirements.
There's ${parameters.numbers} and ${parameters.answers} in the code because I am using lab.js for the looping. They just mean every time the number in the equation and the answer would change. For example, for the first loop ${parameters.numbers} is 200, and the corresponding answer ${parameters.answers} is 194. lab.js would take care of converting these two parameters to actual numbers for each loop of the form.
<form>
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="${parameters.answers}" min="${parameters.answers}"><br>
<button type="submit">OK</button>
</form>
I try to avoid a dramatic alert dialogue for this, just a non-intrusive message like the default style would be good. If you want to recreate the default "values must be greater than or equal to ..." message, just replace the parameters like this would be good:
<form>
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" max="194" min="194"><br>
<button type="submit">OK</button>
</form>
I agree with #ElroyJetson that putting the answer inside the tag is not a good idea, but I focused this answer on the way you can set and unset the error message.
I used jQuery, but this can also be done with plain javascript.
The idea is to group the input tag with a span tag (here inside the div with class input-field).
When the value changes or when the form is submitted (in this case when the value changes), you remove any previous error message from the span tag, and then perform the validation. If there is an error you set it in the span tag.
In this way the error message will show below the input element.
To try it fill in an answer and click outside of the input box.
$(document).ready(function(){
$(".input-field").change(function(){
let $inputField = $(this);
let $input = $inputField.find("input");
let $errorMsg = $inputField.find("span.err-msg");
let max = Number($input.data("max"));
let min = Number($input.data("min"));
$errorMsg.text("");
let v = Number($input.val());
if(v < min || v > max){
$errorMsg.text("Invalid answer");
}
});
});
.err-msg{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="input-field">
<label for="algebra">200 - 6 = ?</label><br>
<input name="algebra" type="number" id="algebra" required="" data-max="194" data-min="194"><br>
<span class="err-msg"></span>
</div>
</form>
Don't set the correct answer with min & max. Instead, just call a javascript function by giving your button tag an onClick to evaluate if the user's answer is correct.
<button onclick="evaluateAnswer('.algebra');" class="submitBtn" >OK</button>
Then your javascript should look something like this:
function evaluateAnswer(cssClass){
var usersAnswer = $(cssClass).val();
var actualCorrectAnswer = 100;
if(usersAnswer == actualCorrectAnswer){
//Do something to proceed
}else{
alert('Sorry, your answer is incorrect');
}
}
Also, I just noticed that you did not want to alert as-in a javascript alert. What you could do is style your message and give it a css class that has the property display:none. Then when you want to show the message when user enters the wrong answer, you can use javascript to remove the class, and also use javascript to add the class back when user enters correct answer.
Edit
You should maybe store your correct answers in a database, evaluate it's correctness serverside, and use Ajax to display the message to prevent users from being able to right-click -> view source and look at the answers in your client-side code
My current solution is like this. There is invisible html elements which stores the correct answer, and the js script validates if the input is correct. Again, the ${} parts represents variables that change in each loop.
html part
<main class="content-horizontal-center content-vertical-center">
<form name="mathEvaluation">
<label for="algebra">${parameters.numbers} - 6 = ?</label><br>
<input name="answer" type="number" id="answer" required="" size="3"><br>
<button type="submit">OK</button>
<input type="hidden" id="hidenAnswer" value=${parameters.answers} />
</form>
</main>
js part
this.options.validator = function(data) {
if(mathEvaluation.answer.value == mathEvaluation.hidenAnswer.value){
return true
} else {
alert("Please enter the correct number.")
}
}

How can I deserialize a multilevel JavaScript object to an HTML form?

EDIT: there are one conceptual error and one technical error on the problem definition so this question should better be closed instead of sanitized. When I have time to redefine the problem I'll post it again. Please help voting to close because of unspecific.
There are lots of info and questions about serializing complex HTML forms to its corresponding JavaScript object (for example this).
Here is a sample of that process: having this form
<form>
<input type="text" name="scalar" value="1">
<input type="text" name="array[0]" value="1">
<input type="text" name="array[1]" value="2">
<input type="text" name="array[2]" value="3">
<input type="text" name="object[subscalar]" value="1">
</form>
And getting from it this javascript object
{
"scalar": 1,
"array": [1, 2, 3],
"object": {
"subscalar": 1
}
}
But how can I do the inverse job?
Our goal is to perform a native POST targeting a separate browser window. We have a complex JavaScript object and we were sending through an AJAX POST, so we were using the object directly as jQuery.ajax data parameter. But now we need to create a real form in the DOM containing the inputs and values with all that brackets syntax, and then natively submit it targeting a specific frame.
jQuery usage is optional. Already existing method, library, etc is preferable against a custom snuppet. This isn't about not being able to code it, it's about not being sure we need to reinvent the wheel.
Thanks in advance.
function parseform(elem,parent=""){
this.html="";
this.parent=parent;
if(typeof elem=="Array"){
var counter=0;
elem.forEach(function(a){
this.html+=new parseform(a,this.parent+"["+counter+"]").html;
counter++;
});
}
if(typeof elem=="String"){
this.html+="<input name='"this.parent+"["+elem+"]' />";
}
//object in progress
if(typeof elem=="Object"){
for (var key in elem) {
if (p.hasOwnProperty(key)) {
this.html += new parseform(elem[key],this.parent="["+key+"]").html;
}
}
}
}
Use like this:
code=new parseform(yourjsondecoded).html;
I know you dont want code, but i dont think that theres an api for something so specific

How to pass an a value from a page to another using javascript

How do you pass a value or an array from one page to another in html using javascript. I'm not allowed to use local storage or sessions only pass the variable from page to page. I'm sending values from a radio button. I intend to store the results in array as i am keeping track of the users answer to display the result at the end. How do i send an array to quiz_5.html? I intend to keep passing the array instead of using a cookie or local storage as i am not permitted to.
Below is My code:
<div>
<form>
<input type="radio" name="radio" value="correct" class="firstRow"> NASA.Gov
<input type="radio" name="radio" value="incorrect" class="secondRow"> Data.Gov <br>
<input type="radio" name="radio" value="incorrect" class="firstRow"> Facebook
<input type="radio" name="radio" value="incorrect" class="secondRow"> XYZ.net <br>
<input type="button" value="Submit & Next Question" onclick="getAnswer4(this.form)" class="firstRow">
<input type="button" value="Cancel & Clear Selection" onclick="clearOptions(this.form)" class="secondRow">
</form>
</div>
Javascript code:
function getAnswer4(form) {
var a[];
var value;
var checked = form.querySelector("input[type=radio]:checked");
if(!checked) {
alert('Please select an answer');
return;
}
else{
value = checked.value;
}
a.push(value);
location.href = "quiz_5.html";
}
You should just have one HTML button for the entire form. First, let's fix that form tag:
<form name='form' id='form' method='get' action='quiz_5.php'>
Now let's add a submit button to the bottom of the form:
<input type='submit' name='sub' id='sub' value='Submit' />
On quiz_5.html
var pre = onload;
onload = function(){
if(pre)pre();
var resultObject = {};
var fs = location.search.replace('?', '').split('&');
for(var i=0,l=fs.length; i<l; i++){
var z = fs[i].split('=');
resultObject[decodeURIComponent(z[0])] = decodeURIComponent(z[1]);
}
/* resultObject now has values based on name attibute
for instance resultObject.radio will hold value of name='radio' where it's checked */
}
Sorry if my comments seemed harsh, but I am all about new coders learning the basics themselves without relying on having the answers provided. Just to show it can be done - I just created three HTML pages. Created a form in the first two - each with your questions (questions 1 and 2 in the first page and question 3 in the second page), and passed the form values to the next one, using nothing more than html.
Then using only JavaScript on the second and third pages, I grabbed the values out of the URL and did stuff with them. On page two, I re-used the values from page 1 (think how that might have been done and why it is useful) so that all three values are passed to page 3 which then used JavaScript only to grab the 3 values, display them on the page (as shown in the code section below) and calculate the total and the percentage of answers that are correct. Note that I answered the questions so that I got question 2 incorrect.
Note that I am not giving the code used, but will give you the URL of the pages so that you can see the outcome of the previous two pages and can then start to think how I achieved this.
numbers1.html
numbers2.html?one=correct&two=incorrect
numbers3.html?one=correct&two=incorrect&three=correct
Question 1: correct
Question 2:incorrect
Question 3:correct
2/3
0.67% correct
Not a traditional answer I know, but it is not ideal for learners simply ask for the answer to be provided, especially when in 10 minutes I was able to put together the three pages that achieved the outcome. If you do not try then you will not learn for yourself.

Store data on page to variables using Javascript/JQuery

So I am trying to store data to variables on the page when a button is clicked, there are multiple buttons and it needs to store data for that specific button. Each one of these buttons is nested inside a <form onsubmit></form> all the data I need to extra is within this form in different <input> and <div> tags. So using javascript or jquery how can I select the value of a specific and tag. So when the button is clicked on it adds this product to the cart, I want to take the productNumber, price, and quantity and store them to my own variables. When the button is clicked the forum calls onsubmit="ShoppingCartAddAJAX( this ); so I want to store this data in the ShoppingCartAddAJAX function.
Here is what one of the forms on the page looks like.
<form method="post" name="addtocart-501" onsubmit="ShoppingCartAddAJAX( this ); return false;">
<input type="hidden" name="formName" value="ShoppingCartAddAJAX" />
<input type="hidden" name="productNumber" value="758201" />
<input id="qtyproduct" type="hidden" class="hiddenqty" name="dmst_Qty_2805" value="1" />
<div class="price">
<div class="pricenew singleprice">
$7.99
</div>
</div>
</a>
</div>
</div>
</li>
</form>
So I have been trying to get this data by doing something like this.
var pn = $('input[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
In my javascript file the function looks something like this:
function ShoppingCartAddAJAX(formElement, productNumber) {
var pn = $('formElement.input[name$="productNumber"]').val();
var aa = $('formElement[name$="productNumber"]').val();
var qty = $('input[id$="qtyproduct"]').val();
}
But with alot more code... just showing that the function is passing in formElement and a productNumber.
But this is giving me the product number and quantity of the first product on the page, I need the data for which ever button the user decides to click on and there are multiple ones on the page not just one. I hope that when the button is clicked and that function is fired there is a way to look what forum it came from and then extract that data. I would also like to be able to get the price but it is stored in <div class="pricenew singleprice"> $7.99</div>.
Any help is greatly appreciated.
You are getting the product number and quantity of the first record since you have multiple input fields in the form with the name of productNumber(according to your description). So what basically happens here is when you call $('input[name="productNumber"]').val() jquery returns you the value of the first input field. Instead of that, do something like this inside your ShoppingCartAddAJAX function.
function ShoppingCartAddAJAX(form)
{
// Find child an element inside our form with the id of "qtyproduct"
// I used "find("#qtyproduct")" method so it searches anything nested inside your specific form element
// You can use "children("#qtyproduct")" method also
var qty = $(form).find("#qtyproduct").val();
var pn = $(form).find("input[name='productNumber']").val();
var pp = $(form).find(".pricenew.singleprice").text();
}

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources