Creating a quiz page using Javascript - javascript

I was trying to create a simple quiz page using Javascript. Else it went well, but after I run this code in browser, on pressing submit button the DOM text appeared in paragraph(through Script) disappears just after a flash. I had expected the text to remain on screen until the next action. Please help me troubleshoot this problem.
Thank you
Code
<!DOCTYPE HTML>
<html>
<head>
<title>
Quiz
</title>
<script type = "text/Javascript">
function checkAnswers()
{
var myQuiz = document.getElementById( "myQuiz" );
if ( myQuiz.elements[ 2 ].checked )
document.getElementById("demo").innerHTML = "Congrats, Thats the Right answer";
else
document.getElementById("demo").innerHTML = "Woops!! The Correct answer is 'Mouse'.<br>Click 'Next' to Proceed";
}
</script>
</head>
<body>
<br><br><br><br><br><br>
<form id = "myQuiz" onsubmit = "checkAnswers()" action = "">
Which among the following is readily found in computers ?
<br><br><br>
<input type = "radio" name = "radiobutton" value = "A" /><label> Zebra</label>
<input type = "radio" name = "radiobutton" value = "B" /><label> Girrafe</label>
<br><br> <input type = "radio" name = "radiobutton" value = "C" /><label>Mouse</label>
<input type = "radio" name = "radiobutton" value = "D" /><label>Mosquito</label>
</div><br><input type = "submit" name = "submit" value = "Submit" />
<br>
<p id = "demo" "> </p>
</form>
</body>
</html>

Make the following changes:
HTML
<form id = "myQuiz" onsubmit = "checkAnswers(event)" action = "">
JS
function checkAnswers(event) {
event.preventDefault();
...
}
preventDefault cancels the form submit event which is causing the page to reload and your text to disappear.
DEMO

Just return "false" inside the onSubmit parameter, like this:
<form id = "myQuiz" onsubmit = "return false" action = "">
And invoke the checkAnswers() function when someone clicks the button;
<input type = "submit" name = "submit" value = "Submit" onclick="checkAnswers()" />

Related

How can I enable / disable form fields from within the form tag?

I am trying to enable / disable inputs inside a form using a checkbox. For some reason, when I place the checkbox INSIDE the form tag my javascript function won't work.
This works:
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<form id = 'form'>
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
However, when I try to move the input id = 'check' INSIDE the form tag, the function won't work:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'check()' checked />
<input type 'text' id = 'text' disabled />
</form>
<script>
function check() {
var c = document.getElementById("check");
if (c.checked == true){
document.getElementById("text").disabled = true;
} else {
document.getElementById("text").disabled = false;
}
}
</script>
This must be something very silly, but I can't figure it out.
Please notice: I am trying to use this inside a bigger, multi-page form that asks from residence information first and then, in the second tab/page, asks for mailing info. So, if the checkbox is checked I want mailing info fields to be disabled.
Any idea? Help is appreciated!
It looks like that inside a form the check variable what you want to call will be the HtmlNode itself because it got the same name(id).
So in you code with check() you are try to call the HtmlNode which is for sure not a function.
If you rename the function to something like test it will work fine.
or use the addEventListener method to pass the function itself and this will also keep your code cleaner.
You can have a look in this fiddle:
https://jsfiddle.net/k7xjv0Ls/
So this thing is probably a possibility to make it easy to manage forms it self. e.g. You don't need any <script> here at all, if you do something like this:
<form id = 'form'>
<input type = 'checkbox' id ='check' onchange = 'text.disabled = check.checked' />
<input type='text' id = 'text'/>
</form>
Explanation for all modern browsers like "Firefox, Chrome, Safari":
the id of an HTMLNode usually goes to the window object as an attribute to reference the HTMLNode itself.
If the HTMLNode is a input field AND it is inside a form tag it will always shadow all kinds of variables (Named functions, vars, consts and lets) but just inside the "Event Attribute" of the HTML, not in the javascript files or all what is inside the <script> tag.
In your case window.check is ambiguous - it could be window.check the function or window.check the field with id="check"
Try to never reuse function, var an element names/IDs
To dix your immediate issue, just rename and pass the checkbox
function checkIt(theCheck) {
const c = theCheck.checked
document.getElementById("text").disabled = c;
}
<form id='form'>
<input type='checkbox' id='check' onchange='checkIt(this)' checked />
<input type='text' id='text' disabled />
</form>
I however STRONGLY recommend to use event listeners
window.addEventListener("load", function() {
document.getElementById("check").addEventListener("change", function() {
document.getElementById("text").disabled = this.checked;
});
});
<form id='form'>
<input type='checkbox' id='check' checked />
<input type='text' id='text' disabled />
</form>

How to get the value of input fields of a particular form on which i clicked ,all the forms and their input have the same class but different value

i get all the forms generated by a PHP while loop so i can not change their id and classes..they all come in the DOM with same id and class but every form input has their own distinct value ...all i want is,,if i click on submit of a particular form i want the jquery to get the input value only of that specific form .
<form class ='myform' >
<input type = "hidden" name ="fname" value = "sam">
<input type = "submit" value = "Submit">
</form>
<form class = 'myform'>
<input type = "hidden" name = "fname" value = "olivia">
<input type = "submit" value = "Submit">
</form>
<form class = 'myform'>
<input type = "hidden" name = " fname " value = "justien">
<input type = "submit" value = "Submit">
</form>
<scirpt >
----here i want the solution
</script>
You could either add a counter into the loop statement for creating the myForm.
`<form class = 'myform${counter}'>`
This would make the forms have a unique class but would make CSS difficult.
Alternatively, you could select the parent of the input field
$('input[value="justien"]').parent();
That should work
It works for me like a charm
$(document).ready(
$(".myforms']").submit(function(e) {
e.preventDefault();
var f_name = $(this).children("input[name='f_name']");
alert(f_name.val());
})
);

Load whole page before javascript runs

I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}
You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>
You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.

Jquery not returning the values in form INPUTs

I have a login form on a modal jquery dialog with the usual 2 text INPUTs. When I enter a login name and password then click the submit, the call back function is called.
The first thing the callback does is try to extract the values of the two INPUTs, but the values returned are empty strings (I have a breakpont here, and have even stepped through the jquery processing of the objects - they objects are correctly identified as the fields on the form, but value="" for both).
At this point I can still see the values in the form, and when the callback exits and the focus goes back to the form, the values are still in the INPUTS. I also tried .prop("value") rather than .val(), but the result was the same.
I just can't figure why I can't read the values - any help appreciated.
<form id="cp-loginform" action="/cypo/index.php" method="POST" >
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50"></p>
<input type="submit" id="cp-submit" name = "submit" onclick="ProcessLogin()" ></p>
</form>
function ProcessLogin() {
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
}
PROBLEM RESOLVED:
I felt that this was a scope issue. The form itself was obviously OK (if submitted from the dialog it worked) - it was just the attempt to check the INPUT values using jquery that wasn't working.
I found that my select had to start with the dialog element and include a descendent path to my INPUTs. It's as if the dialog puts a wrapper around the elements inside so they are no longer visible as owned by the document.
If I login with xxx and zzz and step therough the following code I see this:
var loginval = $("#cploginname").val(); << = ""
var passwordval = $("#cppassword").val(); << = ""
var loginval = $("#cp-loginform #cploginname").val(); << = ""
var passwordval = $("#cp-loginform #cppassword").val(); << = ""
var loginval = $("#cpdialog #cp-loginform #cploginname").val(); << = "xxx"
var passwordval = $("#cpdialog #cp-loginform #cppassword").val(); << = "zzz"
console.log(loginval.concat(" ",passwordval));
I can't say I understand what's going on, but I have a solution so I am happy. Thanks to all who answered.
FINAL WORD
Thanks to #CMedina, I now understand. The form was defined in a hidden DIV at the top of my BODY section, and I passed $("#loginform") to a f() that created the dialog. The dialog was added to the DOM just before the . I had missed the fact that my original form was still in the DOM, so I was referencing that, not the dialog copy. When I included the dialog wrapper in the path, I finally 'found' the second copy.
Your button is the type submit (their natural behavior is to send the form). Remove the onclick in your button html.
<input type="submit" id="cp-submit" name = "submit">
You must add preventDefault to prevent submit the form and do what you want. Add the code JS for the button onclick event
$("#cp-submit").on("click", function(e){
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
console.log(loginval.concat(" ",passwordval));
});
Result: https://jsfiddle.net/cmedina/svjqb2a4/
Try it :
<html>
<head>
</head>
<body>
<form id="cp-loginform" action="/cypo/index.php" method="POST">
<input type="hidden" name="Login" value="Login">
<input type="hidden" name="pp" value="0" />
<input type="text" id="cp-loginname" name = "loginname" placeholder = "Login ID" class="loginforminput cp-width-50" autofocus >
<input type="password" id="cp-password" name = "password" placeholder = "password" class="loginforminput cp-width-50">
<input type="submit" id="cp-submit" name ="submit" onclick="ProcessLogin(event)">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function ProcessLogin(e) {
e.preventDefault();
var loginval = $("#cp-loginname").val();
var passwordval = $("#cp-password").val();
alert(loginval.concat(" ",passwordval));
}
</script>
</body>
</html>

How to get text from textfield and pass it as a parameter to a javascript function

I have a textfield which is supposed to change an element on the page with the text inside it when a submit button is pressed. I am passing the value to a javascript function. It doesn't work, can anyone tell me how to do it/what i'm doing wrong?
Here is my code:
<html>
<head>
<script type = "text/javascript">
function submitText(string, id)
{
document.getElementById(id).innerHTML = string;
}
</script>
</head>
<body>
<p id = "Datepara" style = "font-family:comic sans ms;color:orange;text-align:center;font-size:25px;">
Date Created: 24/9/12 <br /><br /><br/>
</p>
<input id = "changetext" type = "text" value = "Enter text to display text in this webpage!"/>
<input id = "submit" type = "button" onclick = "submitText('Datepara','document.getElementById("changetext").value;'" value = "Submit" />
</body>
</html>
do this
<input id = "submit" type = "button" onclick = "submitText('Datepara','changetext')" value = "Submit" />
javascript
function submitText(divid,txtid)
{
document.getElementById(divid).innerHTML = document.getElementById(txtid).value;
}
This is what I changed on your code: I switched the order of your parameters on submitText function, I removed the quotes around document.getElementById("changetext").value since you were passing a string and not the value of the input control
function submitText(id, string)
{
document.getElementById(id).innerHTML = string;
}
<input id="submit" type="button"
onclick="submitText('Datepara', document.getElementById('changetext').value)"
value="Submit" />
'document.getElementById("changetext").value;' is a string literal, not the value property of a gEBId call.
"submitText('Datepara','document.getElementById(" is the value of the onclick attribute. Watch your quotes.
submitText(string, id) takes a string then an id, not an id then a string.

Categories