I have an assignment for my course I am battling with. I have to save user input (from answers to 9 math problems) into an array when the "submit" button is clicked and then use the array to perform functions like checking how many answers are correct and showing hit rate. I have written the html with a table and form combination but not sure how to start with the javascript.
Thanks!
Give id to all text box like this
I have included one text box, You can include it how much ever u want
<input name="text" type="text" maxlength="512" id="answer1" />
<button onclick="myFunction()">Submit</button>
function myFunction(){
var array= [];
var value = document.getElementById('answer1').value
array.push(value);
for(int i=0; i< array.length; i++){
//perform your operations
}}
Related
I'm rather new to programming and super new to Flask. I'm implementing an html page which has a few filters on the left and it shows the results on the right.
For example a filter might be "2 people room". Selecting it, it would show only 2 people rooms in the div on the right.
All my data is in a DB.
What's the best way to implement it?
I'm thinking of this way:
- Implement onclick JS function that, when clicking on 2people room filter, it would select a subset of the data (only the 2 people rooms) and then create html for all that data (in Jinja2).
Is here a better way to do so?
thanks
You could use a HTML checkbox.
You could then have some JavaScript that displays the results based on which checkboxes are checked or not.
EDIT
I have quickly made a form here, using pure HTML/JavaScript. What you could do is make a GET request to your flask server using the contents of array. Or just make a basic SQL query to your database: SELECT houses FROM table WHERE rooms=array. ( That's not a valid SQL query, you will have to pass in the numbers properly)
<!DOCTYPE html>
<html>
<body>
<p>Filter Menu</p>
<form action="/action_page.php">
<input type="checkbox" name="room" value="0">Studio<br>
<input type="checkbox" name="room" value="1">One bed<br>
<br>
<input type="button" onclick="myFunction()" value="update filter">
</form>
<script>
function myFunction() {
var form = document.forms[0];
var array = [];
var i;
for (i = 0; i < form.length; i++) {
if (form[i].checked) {
array.push(form[i].value);
}
}
console.log(array)
// Make an SQL query with array
}
</script>
</body>
</html>
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 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.
I have a field in my page named as "myField"
Now this is dynamic So there are 2 cases i.e. it can be just 1 field as;
<input type="text" name="myField" />
OR there can be 2 fields as below;
<input type="text" name="myField" />
<input type="hidden" name="myField" />
I use the following code to access the value in JS;
document.forms[0].myField[0].value
However, this does not work if there is only 1 field (as in the first case)
How do I write dynamic JS code to handle the same?
It should be cross browser compatible.
Yes, because in the first case you should use document.forms[0].myField.value.
I'd suggest to retrieve elements with getElementsByName() method:
var val = document.getElementsByName("myField")[0].value;
better way is to give a unique ID to each element and then get it with
document.getElementById(id).value
Have a look at JQuery, and here's some information on how to get the value out.
provided there is at least one element name "myField"
var count = document.forms[0].myField.length;
for(var i=0; i < count; i++){
// do something with document.forms[0].myField[i].value
console.log(document.forms[0].myField[i].value);
}
fiddle : http://jsfiddle.net/HtrrT/
I used the following code:
<html>
<head>
<script type="text/javascript" language="javascript">
function doit(page) {
var entry = page.entry;
var flag = false;
document.write(entry.length);
}
</script>
</head>
<body>
<span id="error_checkbox" style="color: blue;"> </span>
<form name="subscribeTablePage">
<input type="checkbox" id="entry" value="1"/> <label>1</label><br/>
<input type="button" value="Submit" onclick="doit(document.subscribeTablePage)"/>
</form>
</body>
</html>
Why is the value of entry.length undefined? At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Use Case :
I am going to retrieve rows from Database and in that case I need to check the number of checkboxes checked to perform deletion operation !! Please give ur valuable comments to sort this problem
entry is id of your input
it should be name if you want to refer it in that way..
<input type="checkbox" name="entry" id="entry" value="1"/>
To access it form element by id you have to use
document.getElementById('idOfElement')
Also I dont find your objective for using length. you can get size of the input not length.
If you want to find number of checkboxes checked then probably in javascript you can check by writing a script as below
var inputElems = document.getElementsByTagName("input"),
count = 0;
for (var i=0; i<inputElems.length; i++) {
if (inputElems[i].type === "checkbox" && inputElems[i].checked === true) {
count++;
}
}
You are trying to access the checkbox #entry. add the attribute name="entry" like so.
<input type="checkbox" id="entry" name="entry" value="1" />
Form objects are accessed by their name property.
As for the Javascript, you want value, not length.
document.write(entry.value);
length represents the length in characters of a given string.
Why is the value of entry.length undefined?
Because form.entry references the element, and the element doesn't have a length property. You want:
entry.value.length;
At the same time when I tried with multiple checkboxes, the value of entry.length was the number of checkboxes used!
Because if more than one form control has the same name, form.controlName references a collection of all the controls with the same name. HTML Collections have a length property that is the number of elements in the collection.
Also, the line:
> document.write(entry.length);
will clear the entire document, likely you want:
alert(entry.value.length);
// or
console.log(entry.value.length);
You may find it useful to read the entire section about forms in the HTML 5 specification, and also relevant parts of the HTML 4.01 standard.