I have four main HTML files:
introPage.html, formOne.html, and radio buttons on submit should go to pageThree.html or pageFour.html. I have two switch statements for pages 3 and 4 that direct to their segmented
pages.
On submit, I would get stuck on page 2, and im not sure what is causing this issue.
Previously I was using innerHTML instead of different HTML files, and it worked. But when I swapped all the lines of innerHTML for window.location.href, this issue started happening.
introPage.html:
<html>
<head></head>
<body>
<button type="button" id="subButton">Next...</button>
</body>
<script type="text/javascript" src="jsFile.js"></script>
</html>
formOne:
<html>
<head></head>
<body>
<input id="rb1" type="radio" name="option1" value="pageOne" /> 1
<input id="rb2" type="radio" name="option1" value="pageTwo" /> 2
<button type="button" id="subButton">Next...</button>
</body>
<script type="text/javascript" src="jsFile.js"></script>
</html>
jsFile.js:
var cPage = 1;
var testType;
var sb = document.getElementById("subButton");
sp.addEventListener("click", function () {
optionRes()
nextPage()
}
function optionRes() {
let option1 = document.getElementsByName("option1");
for (let i = 0; i < option1.length; i++) {
if (option1[i].checked) {
testNumber = option1[i].value;
}
}
}
function nextPage() {
switch (testNumber) {
case pageOne:
pageThreeSwitch()
break;
case pageTwo:
pageFourSwitch()
break;
default:
pageThreeSwitch()
}
}
function pageThreeSwitch() {
switch(cPage) {
case 1:
cPage++;
pageFive();
break;
case 2:
cPage++
pageSevin();
}
}
function pageFourSwitch() {
switch(cPage) {
case 1:
cPage++;
pageSix();
break;
case 2:
cPage++
pageEight();
}
}
Related
I have to create a calculator but i have to use separate functions for add , subtract , division and multiply
there should be an equal to (=) button which upon clicking should display the result
operators should be selected using the dropdown box
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<script type="text/javascript">
function add()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a+b
document.getElementById("answer").innerHTML=c;
}
function sub()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a-b;
document.getElementById("answer").innerHTML=c;
}
function mul()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a*b;
document.getElementById("answer").innerHTML=c;
}
function div()
{
var a=parseInt(document.getElementById("firstnumber").value);
var b=parseInt(document.getElementById("secondnumber").value);
var c=a/b;
document.getElementById("answer").innerHTML=c;
}
</script>
<p>First Number: <input id="firstnumber"></p>
<p>Second Number: <input id="secondnumber"></p>
<select id="operators">
<option value="add" onclick="add()">+</option>
<option value="sub" onclick="sub()">-</option>
<option value="mul" onclick="mul()">*</option>
<option value="div" onclick="div()">/</option>
</select>
<button onclick="add.call(this);sub.call(this);mul.call(this);div.call(this);">=</button>
<p id="answer"></p>
</body>
</html>
i think thats what you were looking for.
make sure to read what i wrote under the code
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>calculator</title>
</head>
<body>
<h1 align="center">calculator</h1>
<p>First Number: <input id="firstnumber" /></p>
<p>Second Number: <input id="secondnumber" /></p>
<select id="operators">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">*</option>
<option value="div">/</option>
</select>
<button id="calcBtn">=</button>
<p id="answer"></p>
<script src="script.js"></script>
</body>
</html>
script.js:
document.getElementById("calcBtn").addEventListener("click", () => {
let operator = document.getElementById("operators").value;
let a = parseInt(document.getElementById("firstnumber").value);
let b = parseInt(document.getElementById("secondnumber").value);
switch (operator) {
case "add":
add();
break;
case "sub":
sub();
break;
case "mul":
mul();
break;
case "div":
div();
break;
default:
break;
}
function add() {
let c = a + b;
document.getElementById("answer").innerHTML = c;
}
function sub() {
let c = a - b;
document.getElementById("answer").innerHTML = c;
}
function mul() {
let c = a * b;
document.getElementById("answer").innerHTML = c;
}
function div() {
let c = a / b;
document.getElementById("answer").innerHTML = c;
}
});
dont use onclick, give element an id and then add event listenner to it works the same but addeventlistenner is better you can replace .addEventListener("click", () => { with .addEventListener("click", function() {
its up to you
always place your script tag directly above the body tag
use script src instead of script > code, it makes the html more clean
use let instead of var
switch case its like if, but in situations like that better, because its easier to write what to do depending on the value
usage:
switch(variable){
case "variable value":
code
break;
}
i think thats all
For exercise, I've created a small HTML-CSS-JavaScript quiz. The quiz itself works but when I tried to edit a way to check if all radio buttons of the quiz are working (and if not, alert a message to the user), it became broken.
Here is the quiz, with the funcion that checks if the radio buttons are clicked:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
if (document.querySelector('#quiz:not(:has(:radio:checked))').length) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
I tried this code after reading of it in this QA session. I also found this session which deals with jQuery and I don't run jQuery on this HTML page.
Why isn't the condition working in my vanilla JavaScript version?
Looking at your HTML code, there's one proportion that can be useful to solve your problem: you want the same number of checked inputs as the number of labels that describe the boxes. When the numbers don't match it's the indicator that not all questions were answered:
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
const labelCount = document.querySelectorAll('#quiz label').length;
const checkedInputsCount = document.querySelectorAll("#quiz :checked").length;
if (labelCount !== checkedInputsCount) {
return alert("At least one group is blank");
} else {
function showScore() {
totalScore = result;
alert(totalScore);
}
}
}
<form id="quiz">
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
<br>
<label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
<br>
<input type="button" onclick="obcpq()" />
<!-- One Button Chcked Per Question -->
</form>
Try to add every question in a separate div then loop through them and check if the group has at least one checked option radio, then use a flag to store the loop result and finally show the right message, like :
let result = 0;
function right() {
result += 50;
}
function wrong() {
result -= 50;
}
function obcpq() {
var groups = document.querySelectorAll('#quiz div');
var all_checked = true;
for (i = 0; i < groups.length; i++) {
if (groups[i].querySelectorAll(':checked').length==0) {
all_checked = false;
}
}
if (!all_checked) {
console.log('Check please all the radios');
} else {
console.log('showScore');
}
}
<form id="quiz">
<div>
<label>Q1 - X?</label>
<input type="radio" onclick="right()">Yes
<input type="radio" onclick="wrong()">No
</div>
<div> <label>Q2 - Y?</label>
<input type="radio" onclick="wrong()">Yes
<input type="radio" onclick="right()">No
</div>
<input type="button" onclick="obcpq()" value="CHECK"/>
<!-- One Button Chcked Per Question -->
</form>
I currently have a question within my HTML and a radio group with a simple yes or no. I would like to make it so that when the user answers yes, they get an alert that says good job. and when they answer no, the alert says try again and reloads the page.
Here is the html
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300"><br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No<br><br>
<button id="submitBtn">Submit</button>
and here is the current javascript I have
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
}
}
if(radioGroup[i].value="Yes"){
alert("NICE!")
}
if(radioGroup[i].value="No"){
alert("try again!")
}
}
Try the following code for your javascript:
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
if(radioGroup[i].value==="Yes"){
alert("NICE!")
}
if(radioGroup[i].value==="No"){
alert("try again!")
}
}
}
}
I modified your code, I found a couple of things wrong. Your first if statement was not returning true so I added a title. Your last two if statements, I joined them together. Those two if statements where not in your for loop. and I fixed some common Boolean and semicolons errors. Here is the finalalised result:
if (document.title === "Level 3") {
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices() {
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked) {
console.log("You clicked: " + radioGroup[i].value);
if (radioGroup[i].value === "Yes") {
alert("NICE!");
break;
} else {
alert("Try Again!");
break;
}
}
}
}
<head>
<title>Level 3</title>
</head>
<body>
<div id="enterText"></div>
<img src="../img/Window1.jpg" width="500" height="300">
<br>
<input type="radio" name="radio-group1" value="Yes">Yes
<input type="radio" name="radio-group1" value="No">No
<br>
<br>
<button id="submitBtn">Submit</button>
</body>
This code will reload the page if they say no. Also, fixed minor bugs that said that the choice was YES every time.
if (document.title === "Level 3"){
document.getElementById("enterText").innerHTML = "Look at the Picture below, Is it possible for the equation to be true?";
document.getElementById("submitBtn").addEventListener("click", calcChoices, false);
}
function calcChoices(){
var radioGroup = document.getElementsByName("radio-group1");
for (var i = 0; i < radioGroup.length; i++) {
if (radioGroup[i].checked){
console.log("You clicked: "+ radioGroup[i].value);
if(radioGroup[i].value==="Yes"){
alert("NICE!");
}
if(radioGroup[i].value==="No"){
alert("try again!");
location.reload(); //Added this line
}
}
}
}
Hello all: I recently stumbled upon a question about form validation, which I'm currently trying to get working. I got the code from an answer and then customized it to more what I'm needing.:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function Validate(){
if(!validateForm()){
alert("Something happened");
return false;
}
return true
}
function validateForm()
{
var c=document.getElementsByTagName('input');
for (var i = 0; i<c.length; i++){
if (c[i].type=='checkbox')
{
if (c[i].checked){return true}
}
}
return false;
}
</script>
</head>
<body>
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate()" method="get">
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
NOTE: The image is just from a Google Image Search, and is on Wikipedia (I do not own it).
Now, when I originally entered the HTML from the answer into the Tryit Editor at W3 Schools, it would give me a "Something Happened" alert, or do nothing. (I think that's what is was supposed to do).
Still, (now that I have my own questions) it will say "something happened" if nothing is selected, but no matter how many check (over 1 checked) it will just give me the image. Basically, what I want is it to check if ALL or ONLY SOME are checked. If all are checked i want one image, and if only some, I want a different one.
I hope this isn't too confusing, and I appreciate any help :)
P.S.:Here is the question where I got the code: Original Question
Try this for the script section, it will change the form's "action" attribute (which points the form to a the desired URL upon submitting) after validating how many checkboxes are checked:
<script type="text/javascript">
function Validate(formRef){
var checkboxes = getCheckboxes(formRef);
var checkedCount = validateForm(checkboxes);
if(checkedCount == checkboxes.length){
// All are checked!
return true;
} else if(checkedCount > 0) {
// A few are checked!
formRef.setAttribute('action', 'http://upload.wikimedia.org/wikipedia/commons/thumb/2/24/Yahoo!_logo.svg/200px-Yahoo!_logo.svg.png');
return true;
} else {
alert("Something happened");
}
return true;
}
function getCheckboxes(formRef) {
var c = formRef.getElementsByTagName('input');
var checkboxes = [];
for (var i = 0; i<c.length; i++){
if (c[i].type == 'checkbox')
{
checkboxes.push(c[i]);
}
}
return checkboxes;
}
function validateForm(checkboxes) {
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++){
if (checkboxes[i].checked){
checkedCount++;
}
}
return checkedCount;
}
</script>
The form HTML should be updated to pass "this", the reference to the form object being validated, into the Validate() function, to avoid the need to query for it again:
<form name="myForm" action="http://upload.wikimedia.org/wikipedia/commons/3/30/Googlelogo.png" onsubmit="return Validate(this)" method="get">
Try this (will alert first option if one or more but less than 3 checked, will alert second option if exactly 3 checked):
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" name="live" value="yesno">You are alive.
<br>
<input type="checkbox" name="type" value="person">You are a person.
<br>
<input type="checkbox" name="eyes" value="color">Your eyes have color.
<br>
<input value="Submit" type="submit" onclick="
var count = 0;
for(var i = 0; i < document.getElementsByTagName('input').length - 1; i++)
{
if(document.getElementsByTagName('input')[i].checked)
{
count += 1;
}
}
if(count >= 1 && count < 3)
{
alert('First Option');
}else
{
if(count == 3)
{
alert('Second Option');
}
}" />
</body>
</html>
The following should get you on the right path:
function Validate() {
var checkboxes = processCheckboxes();
if (checkboxes.all.length == checkboxes.checked.length) {
alert("All are checked");
} else if (checkboxes.checked.length > 0) {
alert("Some checked");
} else {
alert("None checked");
}
return false;
}
function processCheckboxes() {
var checkboxes = document.querySelectorAll('input[type=checkbox]');
var checked = [].filter.call( checkboxes, function( el ) {
return el.checked
});
return { all: checkboxes, checked: checked };
}
You can then process the checked boxes in whatever manner you like before submitting.
See a working example here: http://jsfiddle.net/jkeyes/Zcu7d/
I want to reset form in firefox browser. When I use previous function in back button, the page is not reset for hidden field. It has previous stage. So, How do I?
<Html>
<Head>
<Title>My Testing for javascript</Title>
<Script type="text/javascript">
function hidetext(){
window.alert('Start save to hidden');
document.getElementById('hid').value = document.getElementById('puttextbox').value;
window.alert('Complete save to hidden');
document.getElementById('puttextbox').value='';
}
function displaytext(){
window.alert('Start display from hidden');
document.getElementById('displaytextbox').value = document.getElementById('hid').value;
window.alert('Complete display from hidden');
}
function resetform(){
document.getElementById('form1').reset();
window.alert('reset is completing.....');
}
</Script>
</Head>
<Body>
<form id="form1">
<div>
Type your hidden text <input type="text" id="puttextbox"/>
<br/>
Display your hidden text <input type="text" id="displaytextbox"/>
<br/>
<input type="hidden" id="hid"/>
<button type="button" id="putbutton" onclick="hidetext();">Put the textbox</button>
<button type="button" id="displaybutton" onclick="displaytext();">Display hidden text</button>
<button type="button" id="resetbutton" onclick="resetform();">Reset</button>
</div>
</form>
</Body>
</Html>
Why not this:
<input type="reset" value="Reset">
? It's HTML-native. Or try this instead:
window.onload = function() {
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = '';
}
};
It clears each input element in the page.
function clearForm(oForm) {
var elements = oForm.elements;
oForm.reset();
for(i=0; i<elements.length; i++) {
field_type = elements[i].type.toLowerCase();
switch(field_type) {
case "text":
case "password":
case "textarea":
case "hidden":
elements[i].value = "";
break;
case "radio":
case "checkbox":
if (elements[i].checked) {
elements[i].checked = false;
}
break;
case "select-one":
case "select-multi":
elements[i].selectedIndex = -1;
break;
default:
break;
}
}
}
That should do the job.
The most simple version is:
document.form1.reset();
However, this resets all input fields to their default value, i.e. the one sent along with the HTML. If you want all fields cleared, you'd need to loop through them all.