I have been struggling for a while with this since I'm not a pro.
The issue: A quiz. After you click answer A and then submit, you will get an
explanation next to answer A. When you then click answer B and then submit you
will get an explanation next to answer B but explanation A about answer A remains.
This has to disappear.
Here is the link: https://plnkr.co/edit/OvcwBzfFte4A0F0NbNSi?p=preview
<style>
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float:right;
width:50%;
}
</style>
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span id="demo3"></span></div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
<script>
document.getElementById("form1").onsubmit = function(e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
</script>
hgf
<div> </div>
You can give each explanation span a class name of "explanation" and clear their texts each time you call myFunction().
Here's a working demo https://plnkr.co/edit/9TIwKXIxP8A01DeKVWuG?p=preview
<style>
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float:right;
width:50%;
}
</style>
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span class="explanation" id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span class="explanation" id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span class="explanation" id="demo3"></span></div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
<script>
document.getElementById("form1").onsubmit = function(e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
var explanations = document.querySelectorAll(".explanation");
for(var x = 0; x < explanations.length; x++) {
explanations[x].innerHTML = "";
}
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
</script>
hgf
<div> </div>
In html, add class to all <input name="variable"> (note that you cannot have duplicating name attribute on multiple input):
<input class="variable" ...>
Add lines in your myFunction() to get inputs that is not checked:
function myFunction() {
var notChecked = document.getElementsByClassName('variable');
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
for (var i = 0, len = notChecked.length; i < len; i++){
notChecked[i].parentNode.lastChild.innerHTML = '';
}
checked.parentNode.lastChild.innerHTML = answer;
}
Related
I'm trying to create a BMR calculation embedded in my site. I have it working except for the gender portion (if male vs female, different calculations)
I understand that I need an adlistener but doesn't seem to be working. I think I am not referencing it properly.
Here's my code:
var theForm = document.forms["RMRform"];
var bmr;
function RMRcalc() {
var weight = document.getElementById("weight").value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var gender = document.getElementById("gender").value;
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
var activitylevel = new Array();
activitylevel["sedentary"] = 1.2;
activitylevel["low"] = 1.3;
activitylevel["moderate"] = 1.5;
activitylevel["high"] = 1.7;
function getActivityLevel() {
var activityLevelamount = 0;
var theForm = document.forms["RMRform"];
var selectedActivity = theForm.elements["activity"];
activityLevelamount = activitylevel[selectedActivity.value];
return activityLevelamount;
}
if (i = this) {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) - 161) * getActivityLevel();
} else {
bmr = ((10 * weight) + (6.25 * height) - (5 * age) + 5) * getActivityLevel();
}
}
document.getElementsByTagName("button")[0].addEventListener("click", function() {
RMRcalc();
document.getElementById('results').innerHTML = bmr;
})
body {
font: 15px gothic, sans-serif;
letter-spacing: 1px;
}
input {
width: 100%;
}
input[type=number] {
border: none;
border-bottom: 1px solid grey;
}
button[type=button] {
background-color: #ddcecb;
border: none;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
color: #95483e;
padding: 16px 32px;
text-decoration: none;
letter-spacing: 1px;
margin: 4px 2px;
}
input[type=text]:focus {
border: 1px solid #555;
}
.form-inline label {
margin: 5px 10px 5px 0;
}
#media (max-width: 800px) {
.form-inline input {
margin: 10px 0;
}
.form-inline {
flex-direction: column;
align-items: stretch;
}
<form action="" id="RMRform">
<label for='gender' class="inlinelabel">
Female </label>
<input type="radio" id="gender" name="gender" value="fem" checked onclick="RMRcalc()" /><br>
<label for='gender' class="inlinelabel">
Male </label>
<input type="radio" id="gender" name='gender' value="masc" onclick="RMRcalc()" /> <br> Weight (kg):<br>
<input type="number" id="weight"><br><br> Height (cm):<br>
<input type="number" id="height"><br><br> Age (years):<br>
<input type="number" id="age"><br><br> Activity Level:
<select id="activity" name="activity">
<option value="sedentary">sedentary (1-2x/week)</option>
<option value="low">low (2-3x/week)</option>
<option value="moderate">moderate (3-4x/week)</option>
<option value="high">high (5x/week)</option>
</select>
</form> <br>
<button type="button" onclick="">
calculate</button>
<p>Your Daily Estimated Requirements</p>
<div id="results"></div>
With this, there's just no calculation showing.
Thanks in advance!
A closing } is missing for the #media query.
There shouldn't be a variable declaration in your if condition: if (var i=this). Remove the var.
Both of your radio input have the same id="gender". Id's should be unique. Consider using a class instead. This will cause problems when you later use the gender variable for your if male vs female calculations because of this selector:
var gender = document.getElementById("gender").value;
For rad to be defined in your loop...
var rad = document.myForm.myRadios;
...you'll need to change myRadios to gender, because that's the name of your radio inputs. You'll also need to give your form the name myForm.
<form action="" id="RMRform" name="myForm">
Perhaps you're looking for something in this region...
function calc () {
const gender = document.querySelector('input[name="gender"]:checked').value,
weight = document.getElementById('weight').value,
height = document.getElementById('height').value,
age = document.getElementById('age').value,
activity = document.getElementById('activity').value;
// calculate base metric value
let metricBase = ((10 * weight) + (6.25 * height) - (5 * age));
// calculate per gender
metricBase = (gender === 'fem') ? metricBase - 161 : metricBase + 5;
// calculate with inline activity values
const bmr = Math.round( metricBase * parseFloat(activity) );
// format caloric intake output
document.getElementById('results').innerHTML = `${bmr.toLocaleString()} calories/day`;
}
// prevents form change listener until after first calculation
let firstCalc = true;
document.getElementById('calc').addEventListener('click', () => {
if (firstCalc) document.querySelector('form').onchange = calc;
firstCalc = false;
calc();
}, false);
body {
}
body, input {
font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
font-size: 14px;
letter-spacing: 1px;
}
input[type="radio"] {
display: inline-block;
width: 1rem;
}
input[type="number"] {
border: none;
border-bottom: 1px solid #ccc;
}
.group {
padding: .5rem 0;
}
<form>
<div class="group">
<label class="radio">
<input type="radio" name="gender" value="fem" checked />
Female
</label>
<label class="radio">
<input type="radio" name='gender' value="masc" />
Male
</label>
</div>
<div class="group">
<label for="weight">Weight (kg):</label>
<input type="number" id="weight" value="79" />
</div>
<div class="group">
<label for="weight">Height (cm):</label>
<input type="number" id="height" value="172" />
</div>
<div class="group">
<label for="weight">Age (years):</label>
<input type="number" id="age" value="22" />
</div>
<div class="group">
<label for="activity">Activity Level:</label>
<select id="activity">
<option value="1.2" selected>Sedentary (1-2x/week)</option>
<option value="1.3">Low (2-3x/week)</option>
<option value="1.5">Moderate (3-4x/week)</option>
<option value="1.7">High (5x/week)</option>
</select>
</div>
<button type="button" id="calc">Calculate</button>
</form>
<p id="results"></p>
Here is what i see (i am quite new to JS so i may not see everything) :
There is no opening head tag (not sure if that's a problem).
The gender radio buttons both have the same id. IDs should be unique. And because of this my guess is that this code should only give you the value for fem no ?:
html:
<input type="radio" id="gender" name="gender" value="fem" checked
onclick="RMRcalc()" />
<input type="radio" id="gender" name='gender' value="masc"
onclick="RMRcalc()" />
js:
var gender = document.getElementById("gender").value;
In your for-loops i would use let instead of var, otherwise you might get in trouble someday. Checkout this post.
for (let i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function () {
I didn't understand this in your function RMRcalc : if (var i = this)
I am working on a form with multiple pages. On one page I have check boxes that I would require at least one to be selected before submission. How can I do that with javascript/html5?
It is all one form that changes pages with javascript. How on the last page can I have the form check, if at least one checkbox has been selected?
var currentTab = 0; // Current tab is set to be the first tab (0)
showTab(currentTab); // Display the current tab
function showTab(n) {
// This function will display the specified tab of the form...
var x = document.getElementsByClassName("tab");
x[n].style.display = "block";
//... and fix the Previous/Next buttons:
if (n == 0) {
document.getElementById("prevBtn").style.display = "none";
} else {
document.getElementById("prevBtn").style.display = "inline";
}
if (n == (x.length - 1)) {
document.getElementById("nextBtn").innerHTML = "Submit";
} else {
document.getElementById("nextBtn").innerHTML = "Next";
}
//... and run a function that will display the correct step indicator:
fixStepIndicator(n)
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("tab");
// Exit the function if any field in the current tab is invalid:
if (n == 1 && !validateForm()) return false;
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form...
if (currentTab >= x.length) {
// ... the form gets submitted:
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].className += " invalid";
// and set the current valid status to false
valid = false;
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class on the current step:
x[n].className += " active";
}
* {
box-sizing: border-box;
}
body {
background-color: #f1f1f1;
}
#regForm {
background-color: #ffffff;
margin: 100px auto;
font-family: Raleway;
padding: 40px;
width: 70%;
min-width: 300px;
}
h1 {
text-align: center;
}
input {
padding: 10px;
width: 100%;
font-size: 17px;
font-family: Raleway;
border: 1px solid #aaaaaa;
}
/* Mark input boxes that gets an error on validation: */
input.invalid {
background-color: #ffdddd;
}
/* Hide all steps by default: */
.tab {
display: none;
}
button {
background-color: #4CAF50;
color: #ffffff;
border: none;
padding: 10px 20px;
font-size: 17px;
font-family: Raleway;
cursor: pointer;
}
button:hover {
opacity: 0.8;
}
#prevBtn {
background-color: #bbbbbb;
}
/* Make circles that indicate the steps of the form: */
.step {
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbbbbb;
border: none;
border-radius: 50%;
display: inline-block;
opacity: 0.5;
}
.step.active {
opacity: 1;
}
/* Mark the steps that are finished and valid: */
.step.finish {
background-color: #4CAF50;
}
<form id="regForm" action="/action_page.php">
<h1>Register:</h1>
<!-- One "tab" for each step in the form: -->
<div class="tab">Name:
<p><input placeholder="First name..." oninput="this.className = ''" name="fname"></p>
<p><input placeholder="Last name..." oninput="this.className = ''" name="lname"></p>
</div>
<div class="tab">Contact Info:
<p><input placeholder="E-mail..." oninput="this.className = ''" name="email"></p>
<p><input placeholder="Phone..." oninput="this.className = ''" name="phone"></p>
</div>
<div class="tab">
<H3 id="subhead">AUDITORIUM ROOM SETUP & EQUIPMENT REQUESTS</H3>
<label><label id="asterisk">*</label>Room Setup (Select all that apply):</label><br><br>
<!-- <p><input placeholder="dd" oninput="this.className = ''" name="dd"></p> -->
<br>
<input id="element_3_1" name="Room-Setup" required type="checkbox" value="Auditorium-Seating-for-300" />
<label class="choice" id="labelinput" for="element_3_1">Auditorium Seating for 300</label>
<br>
<input id="element_3_2" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-for-350" />
<label class="choice" id="labelinput" for="element_3_2">Auditorium Seating for 350 (recommended max for Performances</label>
<label class="choice" for="element_3_3">Auditorium Seating 400</label>
<input id="element_3_3" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Auditorium-Seating-400" />
<label class="choice" for="element_3_4">Round Tables and Chairs</label>
<input id="element_3_4" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Round-Tables-and-Chairs" />
<label class="choice" for="element_3_5">Other (Please note that we cannot change the auditorium setup during your event*)</label>
<input id="element_3_5" name="Room-Setup" class="elementcheckbox" type="checkbox" value="Other" />
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" id="prevBtn" onclick="nextPrev(-1)">Previous</button>
<button type="button" id="nextBtn" onclick="nextPrev(1)">Next</button>
</div>
</div>
<!-- Circles which indicates the steps of the form: -->
<div style="text-align:center;margin-top:40px;">
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
<span class="step"></span>
</div>
</form>
Put a second classname in <div class="tab theFirstTabWithCheckboxes">
This code get that element and counts cheched inputs to a global variable
var checkboxes = document.querySelectorAll("tab.theFirstTabWithCheckboxes input");
var i = checkboxes.length;
window.count_nr_of_checked_boxes = 0;
while (i--) { //count down to 0
if (checkboxes[i].checked) window.count_nr_of_checked_boxes++;
}
With querySelectorAll() you select in the same way as you select in CSS. Note how the dot operator is an and operator and the space operator means "input is inside ..." (it is evaluated from right to left).
Put the following line in the function validateForm()
if (count_nr_of_checked_boxes < 1) valid = false
You dont need to have window. on global variables
I have a quiz where you can see some information about an answer whether it is wrong or right after you submit. After you click on submit, all 3 informatic texts about the answers are shown instead of just for the answer u clicked.
How can you make it that when you click answer A, information A is seen ?
And not Information A B C
document.getElementById("form1").onsubmit = function (e) {
e.preventDefault();
variable = parseInt(document.querySelector('input[name = "variable"]:checked').value);
sub = parseInt(document.querySelector('input[name = "sub"]:checked').value);
con = parseInt(document.querySelector('input[name = "con"]:checked').value);
result = variable + sub + con;
document.getElementById("grade").innerHTML = result;
var result2 = "";
if (result == 0) {
result2 = "I don't think you studied."
};
if (result == 33) {
result2 = "You need to spend more time. Try again."
};
if (result == 66) {
result2 = "I think you could do better. Try again."
};
if (result == 99) {
result2 = "Excellent!"
};
document.getElementById("grade2").innerHTML = result2;
return false; // required to not refresh the page; just leave this here
} //this ends the submit function
function myFunction() {
document.getElementById("demo").innerHTML = "An octagon is an object with 8 sides to it";
document.getElementById("demo2").innerHTML = "Leprosy is a chronic infection";
document.getElementById("demo3").innerHTML = "Yes ! this is correct";
}
.quizbox {
width: 58%;
max-width: 950px;
border: 1px gray solid;
margin: auto;
padding: 10px;
border-radius: 10px;
border-width: 5px;
border-color: #00A7AE;
margin-top: 7%;
text-align: center;
position: relative;
background: #73B7DB;
}
.row {
text-align: left;
color: white;
margin-left: 10%;
}
span#demo, #demo2, #demo3 {
display: inline;
color: green;
margin-right: 30%;
float: right;
width: 50%;
}
<div class="quizbox">
<!-- open main div -->
<h1>Quiz</h1>
<form id="form1" action=" ">
<div class="row"> <h3>Moths are a member of what order?</h3></div>
<div class="row">
<input name="variable" type="radio" value="0" />Octagon <span id="demo"></span></div>
<div> </div>
<div class="row">
<input name="variable" type="radio" value="0" />Leprosy <span id="demo2"></span></div>
<div class="row">
<input name="variable" type="radio" value="33" />Lepidoptera <span id="demo3"></span></div>
<div class="row"> <h3>Question 2</h3></div>
<div class="row">
<input name="sub" type="radio" value="33" />Answer 1 </div>
<div class="row">
<input name="sub" type="radio" value="0" />Answer 2</div>
<div class="row">
<input name="sub" type="radio" value="0" />Answer 3</div>
<div class="row"><h3>Question 3</h3></div>
<div class="row">
<input name="con" type="radio" value="0" />Answer 1</div>
<div class="row">
<input name="con" type="radio" value="33" />Answer 2</div>
<div class="row">
<input name="con" type="radio" value="0" />Answer 3</div>
<p> <input type="submit" onclick="myFunction()" value="Submit" /> </p>
</form>Your grade is: <span id="grade">__</span>
<p id="grade2"></p>
</div>
<!-- close quizbox div -->
<span>fdf</span> <span>fdf</span><span>fdf</span>
fd
Try this:
function myFunction() {
var checked = document.querySelector("input[name = 'variable']:checked");
var value = checked.parentNode.lastChild.id;
var answer;
switch (value) {
case 'demo':
answer = "An octagon is an object with 8 sides to it";
break;
case 'demo2':
answer = "Leprosy is a chronic infection";
break;
case 'demo3':
answer = "Yes ! this is correct";
break;
}
checked.parentNode.lastChild.innerHTML = answer;
}
But better use css for display/hide right answers
I have a validation Form using Javascript. It must validate the name, email and captcha. But through my validation function, the name and email are validated but the captcha is not validated after the onclick of the submit button.
The following functions shows my code:
<script type="text/javascript">
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
var why = "";
if(theform.CaptchaInput.value == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(theform.CaptchaInput.value != ""){
if(ValidCaptcha(theform.CaptchaInput.value) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
// Validate input against the generated number
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('CaptchaInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
} </script>
The following is my html code for the form which i am using:
<form class="form-horizontal" role="form" action='<?php echo
site_url(); ?>/Welcome/insert_support_info' method="post" enctype="multipart/form-data" onsubmit="return validateform()" name="supportus_form">
<br style="clear:both"/>
<h3 style="margin-bottom: 25px; text-align: center;"><u>Let us Know your Interest</u></h3>
<div class="form-group">
<input type="text" class="form-control" name="cm_name" id="fullname" placeholder="Enter Your Name"/>
<input type="text" class="form-control" name="cm_email" id="email" placeholder="Enter Your E-Mail"/>
<input type="text" class="form-control" name="cm_phone" id="phone" placeholder="Enter Your Phone Number or Mobile Number"/>
<textarea class="form-control" name="cm_message" id="message" rows="3" placeholder="Add your Query"></textarea>
<span class="help-block"><p id="characterLeft" class="help-block ">Limit - 100 words</p></span>
<input class="form-control" name="datetime" value="<?php
date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y h:i:s a', time()); echo $date;
?>" type="hidden" />
<!-- START CAPTCHA -->
<br>
<div class="capbox">
<div id="CaptchaDiv"></div>
<div class="capbox-inner">
Type the above number:<br>
<input type="hidden" id="txtCaptcha">
<input type="text" name="CaptchaInput" id="CaptchaInput" size="15"><br>
</div>
</div>
<br><br>
<!-- END CAPTCHA -->
<button type="submit" class="btn btn-success">Submit</button>
</div>
<hr/>
</form>
I have kept the css to show up the captcha form
<style>
.capbox {
background-color: #92D433;
border: #B3E272 0px solid;
border-width: 0px 12px 0px 0px;
display: inline-block;
*display: inline; zoom: 1; /* FOR IE7-8 */
padding: 8px 40px 8px 8px;
}
.capbox-inner {
font: bold 11px arial, sans-serif;
color: #000000;
background-color: #DBF3BA;
margin: 5px auto 0px auto;
padding: 3px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaDiv {
font: bold 17px verdana, arial, sans-serif;
font-style: italic;
color: #000000;
background-color: #FFFFFF;
padding: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
}
#CaptchaInput { margin: 1px 0px 1px 0px; width: 135px; }
</style>
With the Above code, the captcha is not working. I am using captcha for the first time.
Hey You are using conditional tags in improper way . That leads to unknown bugs. Following Javascript code works you correct.
function validateform(){
var cm_name=document.supportus_form.cm_name.value;
var cm_email=document.supportus_form.cm_email.value;
var atpos = cm_email.indexOf("#");
var dotpos = cm_email.lastIndexOf(".");
var captha = document.getElementById("txtCaptcha").value;
var capthaValue = document.getElementById('CaptchaInput').value.replace(/ /g,'');
console.log(typeof captha);
if(capthaValue == "" || captha != capthaValue) {
validCaptcha()
}
if (cm_name==null || cm_name=="")
{
alert("Name can't be blank");
return false;
}
else if(atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
function validCaptcha() {
var why = "";
if(capthaValue == ""){
why += "- Please Enter CAPTCHA Code.\n";
}
if(capthaValue != ""){
if((captha != capthaValue) == false){
why += "- The CAPTCHA Code Does Not Match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
}
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("CaptchaDiv").innerHTML = code;
The page should output and execute a temperature converter...
However,
While I'm wanting to test my program, I keep running into this a blank page type error...
can someone kind of proof read this, because I don't know what I'm missing.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var convertTemp = function(){
var f;
var c;
if($("to_Celsius").checked){
f = parseFloat($("degrees_entered").value);
if(isNaN(f)){
alert("please type in a value ");
}
else{
c = (f-32) * 5/9;
$("degrees_computed").value = c.toFixed(0);
}
}
else{
c = parseFloat($("degrees_entered").value);
if(isNaN(c)){
alert("you must enter a valid number for degrees.");
}
else{
f = c * 9/5 + 32;
$("degrees_computed").value = f.toFixed(0);
}
}
};
var toFahrenheit = function(){
$("degree_label_1").firstChild.nodeValue = "Enter C degrees:";
$("degree_label_2").firstChild.nodeValue = "Degrees F";
clearTextBoxes();
$("degrees_entered").focus();
};
var toCelsius = function(){
$("degree_label_1").firstChild.nodeValue = "Enter F degrees: ";
$("degree_label_2").firstChild.nodeValue = "Degrees C: ";
clearTextBoxes();
$("degrees_entered").focus();
};
var clearTextBoxes = function(){
$("degrees_entered").value = "";
$("degrees_computed").value = "";
};
window.onload = function(){
$("convert").onclick = convertTemp;
$("to_Celsius").onclick != toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
$("degrees_entered").focus();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
}
h1 {
color: blue;
margin: 0 0 .5em;
}
main {
padding: 1em 2em;
}
label {
float: left;
width: 10em;
margin-right: 1em;
}
input {
margin-bottom: .5em;
}
#convert {
width: 10em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert Temperatures</title>
<link rel="stylesheet" href="styles.css">
<script src="convert_temp.js"></script>
</head>
<body>
<main>
<h1>Convert temperatures</h1>
<input type="radio" name="conversion_type" id="to_celsius" checked>Fahrenheit to Celsius<br>
<input type="radio" name="conversion_type" id="to_fahrenheit">Celsius to Fahrenheit<br><br>
<label id="degree_label_1">Enter F degrees:</label>
<input type="text" id="degrees_entered" ><br>
<label id="degree_label_2">Degrees Celsius:</label>
<input type="text" id="degrees_computed" disabled><br>
<label> </label>
<input type="button" id="convert" value="Convert" /><br>
</main>
</body>
</html>
toCelcius != toCelsius ?
Is that it? A silly typo? The rest looks fine... also watch casing. In your JS you have to_Celsius... but in the html... to_celcius... bad habit for sure
Some issues I verified:
in the line if($("to_Celsius").checked){ you refer to to_Celsius id, but it should be to_celsius (lowercase);
in the lines:
$("to_Celsius").onclick = toCelsius;
$("to_Fahrenheit").onclick = toFahrenheit;
Same thing. Replace both the id with to_celsius and to_fahrenheit.
in this line var toCelcius = function(){, the function is named toCelcius. Just rename it to toCelsius (with s).
Working code: https://jsfiddle.net/mrlew/p8w111ms/