so i have made a calculator for my work that sees how much we could save potential clients. All works well, but i cant get the total fee's for all of the boxes to appear. I just don't think i know the right process to get all the "total monthly savings" to add up at the end.
Here is a JSFiddle: https://jsfiddle.net/snn5vhg2/
Here is the page:http://176.32.230.46/sarahmcdonald.com/files/index.html
And here is the code:
<html>
<head>
<title>First Data Calculator</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
body{
background-color:#e5e5e5;
}
#container{
font-family:Tahoma, Geneva, sans-serif;
}
#main{
margin-bottom:50px;
font-size:3em;
text-decoration:underline;
}
#VISABOX{
display:inline-block;
width:238px;
background-color:#fce4d1;
padding:15px;
border-radius:6px;
height:238px;
border:#c9c9c9 solid 1px;
}
.boxes{
display:inline-block;
margin-left:20px;
vertical-align:top;
width:238px;
background-color:#fce4d1;
padding:15px;
height:238px;
border-radius:6px;
border:#c9c9c9 solid 1px;
}
.titles{
margin:0 0 0 8px;
}
.inputs{
margin:7px;
height:25px;
width:200px;
}
.words{
margin:7px 0 0 8px ;
}
.calculators{
margin:7px;
height:25px;
border-radius:5px;
background-color:#F3F3F3;
}
#totals{
margin:30px 0 0 5px;
font-size:1.3em;
}
#finishButton{
font-size:1.3em;
border-radius:7px;
background-color:#F3F3F3;
}
</style>
</head>
<body>
<div id="container">
<h1 id="main">Fee Calculator</h1>
<div id="VISABOX" >
<h4 id="VISA" class="titles">Visa</h4>
<input id="vVol" class="inputs" type="text" placeholder="Visa Volume..."/><br>
<input id="vFees" class="inputs" type="text" placeholder="Visa Fees..."/><br>
<button id="vCalc" class="calculators"> Calculate </button>
<p id="vEMDR" class="words">EMDR=<span id="vEMDRSPAN"></span></p>
<p id="vMonthly" class="words">Monthly Savings=<span id="vMonthlySpan"></span></p>
<p id="vYearly" class="words">Yearly Savings=<span id="vYearlySpan"></span></p>
<p id="vFive" class="words">Five Year Savings=<span id="vFiveSpan"></span></p>
</div>
<div id="MCBOX" class="boxes">
<h4 id="MC" class="titles">MasterCard</h4>
<input id="mcVol" class="inputs" type="text" placeholder="MC Volume..."/><br>
<input id="mcFees" class="inputs" type="text" placeholder="MC Fees..."/><br>
<button id="mcCalc" class="calculators"> Calculate </button>
<p id="mcEMDR" class="words">EMDR=<span id="mcEMDRSPAN"></span></p>
<p id="mcMonthly" class="words">Monthly Savings=<span id="mcMonthlySpan"></span></p>
<p id="mcYearly" class="words">Yearly Savings=<span id="mcYearlySpan"></span></p>
<p id="mcFive" class="words">Five Year Savings=<span id="mcFiveSpan"></span></p>
</div>
<div id="IDPBOX" class="boxes">
<h4 id="IDP" class="titles">Interac</h4>
<input id="idpTrans" type="text" class="inputs" placeholder="# of Trans..."/><br>
<input id="idpFees" type="text" class="inputs" placeholder="IDP Fees..."/><br>
<button id="idpCalc" class="calculators"> Calculate </button>
<p id="idpPerTran" class="words">Per Tran=<span id="idpPerTranSpan"></span></p>
<p id="idpMonthly" class="words">Monthly Savings=<span id="idpMonthlySpan"></span></p>
<p id="idpYearly" class="words">Yearly Savings=<span id="idpYearlySpan"></span></p>
<p id="idpFive" class="words">Five Year Savings=<span id="idpFiveSpan"></span></p>
</div>
<div id="OCBOX" class="boxes">
<h4 id="OC" class="titles"> Other Charges </h4>
<input id="otherCharges" type="text" class="inputs" placeholder="Total Other Charges..." /><br>
<input id="ourCharges" type="text" class="inputs" placeholder="Our Other Charges..." /><br>
<button id="ocCalc" class="calculators"> Calculate </button>
<p id="ocMonthly" class="words"> Monthly Savings=<span id="ocMonthlySpan"></span></p>
<p id="ocYearly" class="words">Yearly Savings=<span id="ocYearlySpan"></span></p>
<p id="ocFive" class="words">Five Year Savings=<span id="ocFiveSpan"></span></p>
</div>
<div id="totals">
<button id="finishButton"> Finish </button>
<p id="monthlyTotal"> Monthly Total Savings=<span id="monthlyTotalSpan"></span></p>
<p id="yearlyTotal"> Total Yearly Savings=</p>
</div>
<script type="text/javascript">
document.getElementById("vCalc").onclick=function(){
var visaVol=document.getElementById("vVol").value;
var visaFees=document.getElementById("vFees").value;
var visaEMDR;
visaEMDR=(visaFees/visaVol*100).toFixed(2);
var visaMonthly=(visaFees-(visaVol*.0171)).toFixed(2);
var visaYearly=(visaMonthly*12).toFixed(2);
var visaFive=(visaYearly*5).toFixed(2);
document.getElementById("vMonthlySpan").innerHTML=" "+visaMonthly+"$";
document.getElementById("vYearlySpan").innerHTML=" "+visaYearly+"$";
document.getElementById("vFiveSpan").innerHTML=" "+visaFive+"$";
document.getElementById("vEMDRSPAN").innerHTML=" "+visaEMDR+"%";
}
document.getElementById("mcCalc").onclick=function(){
var mcVol=document.getElementById("mcVol").value;
var mcFees=document.getElementById("mcFees").value;
var mcEMDR=(mcFees/mcVol*100).toFixed(2);
var mcMonthly=(mcFees-(mcVol*.0178)).toFixed(2);
var mcYearly=(mcMonthly*12).toFixed(2);
var mcFive=(mcYearly*5).toFixed(2);
document.getElementById("mcMonthlySpan").innerHTML=" "+mcMonthly+"$";
document.getElementById("mcYearlySpan").innerHTML=" "+mcYearly+"$";
document.getElementById("mcFiveSpan").innerHTML=" "+mcFive+"$";
document.getElementById("mcEMDRSPAN").innerHTML=" "+mcEMDR+"%";
}
document.getElementById("idpCalc").onclick=function(){
var debitTrans=document.getElementById("idpTrans").value;
var debitFees=document.getElementById("idpFees").value;
var perTran=(debitFees/debitTrans).toFixed(2);
var debitMonthly=(debitFees-(debitTrans*.04)).toFixed(2);
var debitYearly=(debitMonthly*12).toFixed(2);
var debitFive=(debitYearly*5).toFixed(2);
document.getElementById("idpPerTranSpan").innerHTML=" "+perTran+"$";
document.getElementById("idpMonthlySpan").innerHTML=" "+debitMonthly+"$";
document.getElementById("idpYearlySpan").innerHTML=" "+debitYearly+"$";
document.getElementById("idpFiveSpan").innerHTML=" "+debitFive+"$";
}
document.getElementById("ocCalc").onclick=function(){
var otherFees=document.getElementById("otherCharges").value;
var ourFees=document.getElementById("ourCharges").value;
var ocMonthlySav=(otherFees-ourFees).toFixed(2);
var ocYearlySav=(ocMonthlySav*12).toFixed(2);
var ocFiveSav=(ocYearlySav*5).toFixed(2);
document.getElementById("ocMonthlySpan").innerHTML=" "+ocMonthlySav+"$";
document.getElementById("ocYearlySpan").innerHTML=" "+ocYearlySav+"$";
document.getElementById("ocFiveSpan").innerHTML=" "+ocFiveSav+"$";
}
document.getElementById("finishButton").onclick=function(){
var monTotal=
document.getElementById("monthlyTotalSpan").innerHTML=" "+monTotal+"$";
}
</script>
It appears that you just quit when you are 90% finished (hopefully not).
But to finish up you needed to grab the values from the xxMonthlySpan and xxYearlySpan tags, convert them to floats, add them together, and then change the innerHTML of the span tags in the end.
You also did not have <span id="yearlyTotalSpan"></span> so I added that in just to be consistent with everything else you had.
I also rounded to two decimal places for the year total.
Here is a fiddle: https://jsfiddle.net/qkx8h3hy/
Comment if you have any questions.
Related
This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
Closed 1 year ago.
I get 4.5.525 when adding in javascript
this is the answer i have to get 4.5 + .525 = 5.025 but instead of this i get 4.5.525
here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Swinburnes Test Of Dc Shunt Motor</title>
<style>
body {
padding: 25px;
background-color: white;
color: black;
font-size: 15px;
background: var(--primary-color);
transition: background 2s;
}
.dark-mode {
background-color: black;
color: white;
}
</style>
</head>
<body>
<div style="text-align: center;" class="container col-xs-12 col-md-4">
<h1 style="font-size: 2em;">Swinburnes Calculator (Motor) <span><button class="btn btn-dark badge badge-dark "
style=" margin-left: 101px;
font-size: 12px;" onclick="myFunction()">Dark mode</button></span> </h1>
<div class="inpSection">
<div class="amt">
<label for="VL">VL</label>
<input type="number" name="VL" id="VL" placeholder="Enter VL Value In Name Plate"
style="margin: 2%; margin-left: 6%;">
</div>
<div class="time">
<label for="IL">IL</label>
<input type="number" name="IL" id="IL" placeholder="Enter IL Value"
style="margin: 2%;margin-left: 7%; ">
</div>
<div class="rate">
<label for="Ish">Ish</label>
<input type="number" name="Ish" id="Ish" placeholder="Enter Ish Value"
style="margin: 2%;margin-left: 5%;">
</div>
<div class="rate">
<label for="Ra">Ra</label>
<input type="number" name="Ra" id="Ra" placeholder="Enter Ra value" style="margin: 2%;margin-left: 6%;">
</div>
<div class="rate">
<label for="Load">Load</label>
<input type="number" name="Load" id="Load" placeholder="Enter Load value In Name Plate" style="margin: 2%;">
</div>
<div class="rate">
<label for="noLoad">VL</label>
<input type="number" name="noLoad" id="noLoad" placeholder="Enter NoLoad VL value" style ="margin:2%; margin-left: 6%">
</div>
<div class="button">
<button class="btn btn-success" onclick="Calculate()" style="margin: 2%;
text-align: center;
;
margin-top: 5%;">Calculate</button>
<button class= "btn btn-danger" style="margin: 2%;
text-align: center;
;
margin-top: 5%;" onclick="refreshPage()">Reset All</button>
</div>
<script>
function refreshPage(){
window. location. reload();
}
</script>
<div class="result" style="margin-top: 30px;">
<h3 id="si"></h3>
<h3 id="wv"></h3>
<h3 id="Ip"></h3>
<h3 id="Wc"></h3>
<h3 id="toloss"></h3>
<h3 id="Oppower"></h3>
<h3 id="Eff"></h3>
</div>
</div>
<hr style="height:1px;border:none;color:#333;background-color:#333;" />
<p style=" text-align: center;
margin-top: 30px;">Copyright ©️ 2021 AJB</p>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
<script>
function Calculate() {
let vl = document.getElementById('VL').value;
let il = document.getElementById('IL').value;
let ish = document.getElementById('Ish').value;
let ra = document.getElementById('Ra').value;
let ld = document.getElementById('Load').value;
let vlo = document.getElementById('noLoad').value;
let SI = (vl * ld)
document.getElementById('si').innerHTML = "O/P : " + SI;
var Iao = (ld+ish);
console.log(Iao)
var WV = (Math.pow(Iao, 2) * ra)
document.getElementById('wv').innerHTML = "Wv : " + WV;
let IP = (vl * il)
document.getElementById('Ip').innerHTML = "No Load I/P Power : " + IP;
var ip21 = (vl*il)
var WcIa = (il - ish)
var WvIa = (Math.pow(WcIa, 2) * ra)
var Wc = (IP - WvIa)
document.getElementById('Wc').innerHTML = "Wc : " + Wc;
var TLoss = (WV + Wc)
document.getElementById('toloss').innerHTML = " Total Loss : " + TLoss;
var OP = (SI + TLoss)
document.getElementById('Oppower').innerHTML = "Input Power : " + OP;
var ef = (SI / OP) * 100
document.getElementById('Eff').innerHTML = " η % : " + ef;
}
</script>
<script>
function myFunction() {
var element = document.body;
element.classList.toggle("dark-mode");
}
</script>
</html>
when i add IL = 4.5 and Ish = .525 it gives 4.5.525 in the console what to do ?
but the orginal answer it should show is 5.025
rewrite the code and comment it below so i can understand more clearly
when i write same in the javascript it gives me the correct answer
Try something like this:
var lat = (parseFloat(document.getElementById('VL').dataset.value));
That's how to save in variable 'var' the document.getElementById('VL') values and make them float, so now it won't see it as a string and hopefully it will let you sum them and get the number you need.
Hi I have these caculator code, I want to hide the result at the bottom everytime I clicked the "calculate" button on the top, how can I do that? below is my code:
when I clicked on the calculate it should give you result of first box and all the result of the rest box, then you can still change the value from box 2 to box 4, then it will show the final result at the bottom, the issue here is when I go back to the box1 and re-input the value and calculate it, the result at the bottom remain old result, how can I hide it when I re-click the button?? full code see here: https://jsfiddle.net/jackwei/w42yocgv/248/
function calculation() {
var firstValue = document.getElementById("firstValue").value;
var secondValue = document.getElementById("secondValue").value;
var first1Value = document.getElementById("first1Value").value;
var second2Value = document.getElementById("second2Value").value;
var first3Value = document.getElementById("first3Value").value;
var first4Value = document.getElementById("first4Value").value;
var result = document.getElementById("result");
var result2 = document.getElementById("result2");
var result3 = document.getElementById("result3");
var result4 = document.getElementById("result4");
var resultall = document.getElementById("resultall");
var calc = firstValue *3 + secondValue *7 + first1Value *1 + second2Value *3;
var calc2 = (firstValue*1 +first1Value*1)*3 + (secondValue*1+second2Value*1)*5;
var calc3 = firstValue*1 + secondValue*1 + first1Value*1 + second2Value*1;
var calc4 = firstValue*1 + secondValue*1 + first1Value*1 + second2Value*1;;
result.textContent = "Template Build " + calc + " Hours";
result2.textContent = calc2 + " Hours";
result3.textContent = calc3 + " Hours";
result4.textContent = calc4 + " Hours";
resultall.textContent = " Campaign Management " + calc2 + " Hours," + " Deployment " + calc3 + " Hours,"+ " Ongoing " + calc4 + " Hours";
document.getElementById('first3Value').value=parseFloat(firstValue) + parseFloat(first1Value);
document.getElementById('first4Value').value=parseFloat(secondValue) + parseFloat(second2Value);
document.getElementById('first5Value').value=parseFloat(firstValue) + parseFloat(secondValue)+ parseFloat(first1Value)+ parseFloat(second2Value);
document.getElementById('first6Value').value=parseFloat(firstValue) + parseFloat(secondValue)+ parseFloat(first1Value)+ parseFloat(second2Value);
}
$('#first3Value,#first4Value,#first5Value,#first6Value').keyup(function(){ // run anytime the value changes
var first3Value = Number($('#first3Value').val()); // get value of field
var first4Value = Number($('#first4Value').val());
var first5Value = Number($('#first5Value').val());
var first6Value = Number($('#first6Value').val()); // convert it to a floa
$('#result2').html(first3Value*3 + first4Value*5 + "Hours" ); // add them and output it
$('#result3').html(first5Value*1 + "Hours");
$('#result4').html(first6Value*1 + "Hours");
$('#resultbox2').html(first3Value*3 + first4Value*5 + "Hours" );
$('#resultbox3').html(first5Value*1 + "Hours" );
$('#resultbox4').html(first6Value*1 + "Hours" );
});
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
#wrap{
width:400px;
margin:0 auto;
text-align:left;
margin-top:8px;
padding:5px;
padding-bottom:15px;
background:#fff;
font-family:AvenirLTStd, Arial, Helvetica, sans-serif;
font-size:13px;
line-height:16px;
}
#wrap .cont_details fieldset,.cont_order fieldset{
margin:10px;
padding:20px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
-khtml-border-radius: 10px;
border-radius: 10px;
}
#wrap legend{
font-size:16px;
font-family:Georgia, "Times New Roman", Times, serif;
color:#000;
font-weight:bold;
font-style:italic;
padding-bottom:10px;
}
#wrap .cont_details input{
margin-bottom:10px;
color:#000;
}
#wrap .input1:hover,.input1:active{
}
#wrap label{
display:block;
font-size:12px;
color:#000;
font-weight:bold;
}
#wrap label.inlinelabel
{
display:inline;
}
#wrap .cont_order input{
margin-bottom:5px;
}
#wrap .cont_order p{
padding-top:5px;
}
#wrap input[type="radio"]
{
margin-top:8px;
margin-bottom:8px;
}
#wrap input[type="text"]:hover,
#wrap input[type="text"]:active {
background-color: #FAF398;
}
#wrap input#submit
{
margin:10px;
padding-left:20px;
padding-right:20px;
padding-top:10px;
padding-bottom:10px;
}
.totalPrice
{
padding:10px;
font-weight:bold;
background-color:#ff0;
}
#wrap label.radiolabel
{
font-weight:normal;
display:inline;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>Cake Form</title>
<link href="http://files.javascript-coder.com/calculation/styles/cakeform.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body onload="hideTotal()">
<div id="wrap">
<div>
<div class="cont_order">
<fieldset>
<legend>Template Build</legend>
<label >New Template Build</label><br><input type="number" id="firstValue" name="firstValue" onclick="calculateTotal()" /> x Simple (3h)<br>
<input type="number" id="secondValue" name="secondValue" onclick="calculateTotal()" />
x Medium (7h)<br>
<br/>
<label >Adaptions of new templates</label>
<br>
<input type="text" id="first1Value" name="first1Value" onclick="calculateTotal()" />
x Simple (1h)<br>
<input type="text" id="second2Value" name="second2Value" onclick="calculateTotal()" />
x Medium (3h)<br/>
<br/>
<p>
<input type="button" id="calc" onclick="calculation()" value="Calculate">
</p>
<div id="result" class="wrap totalPrice"> </div>
</p>
<div id="resultall" class="wrap totalPrice">
</div>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Campaign Management</legend>
<label >Campaign Integration</label><br>
<input type="number" id="first3Value" name="first3Value" onclick="calculateTotal()" class="cm">
x Simple (3h)<br>
<p>
<input type="number" id="first4Value" name="first4Value" onclick="calculateTotal()" class="cm"> x Medium (5h)
</p>
<div id="" class="wrap totalPrice"> Total: <span id="result2">
</span></div>
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Deployment</legend>
<label >Campaign Deployment</label><br>
<input type="number" id="first5Value" name="first5Value" onclick="calculateTotal()" /> x Per section Per Run<br>
<div id="" class="wrap totalPrice"> Total: <span id="result3">
</fieldset>
</div>
<div class="cont_order">
<fieldset>
<legend>Ongoing</legend>
<label >
Continuous Run (non-automated) + Deployment</label><br><input type="text" id="first6Value" name="first6Value" value="0" onclick="calculateTotal()" />
x Per section Per Run<br>
<div id="" class="wrap totalPrice"> Total: <span id="result4">
</fieldset>
</div>
</p>
<div id="" class="wrap totalPrice">
Campaign Management <span id="resultbox2"></span><br> Deployment <span id="resultbox3"></span><br> Ongoing <span id="resultbox4"></span><br> </div>
</div>
</div><!--End of wrap-->
</body>
</html>
I have a problem with If condition when I want to check a value setting from and AJAX consult.
I made a simple page to show the problem:
Main page: https://testdomain3.000webhostapp.com/Test.php
AJAX response: https://testdomain3.000webhostapp.com/Response.php
With the "Yes" and "No" buttons you set the innerHTML value of Span "txtHint4" to "Yes" or "No" respectively.
If click "Check" button, Span "txtHint6" shows value "Ok" if "txtHint4"=Yes or "Ko" if "txtHint4"=No.
All of this works well setting innerHTML "txtHint4" value with the buttons like said but if I set the value with and AJAX consult (with button "Ask AJAX") the if.. then.. statement executed with "Check" button fails to verify the condition and shows "Ko" when it should show "Ok" because "txtHint4"=Yes.
Its the main code:
<html>
<body>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Yes" onclick="Yes()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px"/>
<input type="button" name="Button" value="No" onclick="No()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px"/>
</div>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Ask AJAX" onclick="Ask()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold; padding:5px"/>
</div>
<div style="border: 1px solid black; width:990px;float:left; margin-top:30px; margin-bottom:0px; font-size:50">
<span id="txtHint4"></span>
</div>
<div style="width:1000px; float:left; margin-top:30px; margin-bottom:30px">
<input type="button" name="Button" value="Check" onclick="Check()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold; padding:5px"/>
</div>
<div style="border: 1px solid black; width:990px;float:left; margin-top:0px; margin-bottom:30px; font-size:50">
<span id="txtHint6"></span>
</div>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Erase" onclick="Erase()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px"/>
</div>
<script>
function Yes(){
document.getElementById("txtHint4").innerHTML="Yes";
;}
</script>
<script>
function No(){
document.getElementById("txtHint4").innerHTML="No";
;}
</script>
<script>
function Check() {
var Text=document.getElementById("txtHint4").innerHTML;
if (Text=="Yes"){document.getElementById("txtHint6").innerHTML = "ok";}
else {document.getElementById("txtHint6").innerHTML = "ko";}
;}
</script>
<script>
function Ask() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {document.getElementById("txtHint4").innerHTML = this.responseText;}
xmlhttp.open("GET", "https://testdomain3.000webhostapp.com/Response.php", true);
xmlhttp.send();
}
</script>
<script>
function Erase(){
document.getElementById("txtHint4").innerHTML="";
document.getElementById("txtHint6").innerHTML="";
;}
</script>
</body>
</html>
And the consult AJAX page:
<?php
echo "Yes";
;?
Thank you in advance
You need to use .trim() function to make sure any unseen spaces are removed from the responseText.
When you add innerHTML its adding unseen spaces to your txtHint4 text. So when checking the if condition just use trim() with you Text.
In addtion, i would also recemned using textContent as oppose to innerHTML since you are only adding simple text and and not HTML text
Live Working Demo:
function Yes() {
document.getElementById("txtHint4").innerHTML = "Yes";
}
function No() {
document.getElementById("txtHint4").innerHTML = "No";
}
function Erase() {
document.getElementById("txtHint4").innerHTML = "";
document.getElementById("txtHint6").innerHTML = "";
}
function Check() {
var Text = document.getElementById("txtHint4").innerHTML;
if (Text.trim() == "Yes") { //use trim() function
document.getElementById("txtHint6").innerHTML = "ok";
} else {
document.getElementById("txtHint6").innerHTML = "ko";
};
}
function Ask() {
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
document.getElementById("txtHint4").innerHTML = req.responseText;
}
};
req.open("GET", "https://cors-anywhere.herokuapp.com/https://testdomain3.000webhostapp.com/Response.php", true);
req.send();
}
<html>
<body>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Yes" onclick="Yes()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px" />
<input type="button" name="Button" value="No" onclick="No()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px" />
</div>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Ask AJAX" onclick="Ask()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold; padding:5px" />
</div>
<div style="border: 1px solid black; width:990px;float:left; margin-top:30px; margin-bottom:0px; font-size:50">
<span id="txtHint4"></span>
</div>
<div style="width:1000px; float:left; margin-top:30px; margin-bottom:30px">
<input type="button" name="Button" value="Check" onclick="Check()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold; padding:5px" />
</div>
<div style="border: 1px solid black; width:990px;float:left; margin-top:0px; margin-bottom:30px; font-size:50">
<span id="txtHint6"></span>
</div>
<div style="width:1000px; float:left">
<input type="button" name="Button" value="Erase" onclick="Erase()" id="button" style="cursor: pointer; font-size:32px; font-weight:bold;padding:5px" />
</div>
</body>
</html>
I'm building a user-submission system where a user can input data and an XML will be exported (which can be read by a different software down the line) but I'm coming across a problem where when I replicate the form for the user to input info, the XML is only taking information from the first.
Any suggestions on how do this?
Personal test code:
HTML:
$(function () {
$('#SubmitButton').click(update);
});
var added = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
var adding = [
'\t\t
<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>
'
].join('\r\n');
function update() {
var variables = {
'channeldescription': $('#channeldescription').val(),
'channelrecordnumber': $('#channelrecordnumber').val(),
'channelhexcolor': $('#channelhexcolor').val(),
'channelbamlink': $('#channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
var finalXML = newXml;
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
added = added + '\n' + adding;
$("body").append($("#Entries:first").clone(true));
}
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<body>
<div id="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea id="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input id="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input id="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">RNA-Seq Data/BAM file Repsitory Link</label>
<input id="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly></textarea>
</div>
</div>
</html>
http://www.w3schools.com/code/tryit.asp?filename=F0TWR6VRQZ3J
Change your ids to classes use a loop to get all the entries
<!DOCTYPE html>
<html>
<head>
<script src="cdnjs.cloudflare.com/ajax/libs/processing.js/1.4.1/processing-api.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
.leftmargin {
margin-left: 2%;
}
.form {
background-color: #CBE8BA;
border-radius: 25px;
margin-left: 2%;
margin-right: 2%;
padding-top: 1%;
padding-bottom: 1%;
}
.forminput {
padding-left: 1.5%;
padding-top: 0.5%;
display: flex;
}
.button_fixed {
position: fixed;
margin-left: 2%;
bottom: 1%;
}
</script>
<script>
$(function () {
$('#SubmitButton').click(function(){
var finalXML = '';
$(".Entries").each(function(i,v) {finalXML +=update(finalXML,v)
$('#ResultXml').val(finalXML);
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(finalXML))
.attr('download', 'bamdata.xml');
$('#generated').show();
});
});
});
var added = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
var adding = [
'\t\t<bam_file desc=\"<?channeldescription?>\" record_number=\"<?channelrecordnumber?>\" hex_color=\"<?channelhexcolor?>\" bam_link=\"<?channelbamlink?>\">',
'\t\t</bam_file>'
].join('\r\n');
function update(finalXML,v) {
var variables = {
'channeldescription': $(v).find('.channeldescription').val(),
'channelrecordnumber': $(v).find('.channelrecordnumber').val(),
'channelhexcolor': $(v).find('.channelhexcolor').val(),
'channelbamlink': $(v).find('.channelbamlink').val()
};
var newXml = added.replace(/<\?(\w+)\?>/g,
function(match, name) {
return variables[name];
});
return newXml;
}
$(function () {
$("#CloneForm").click(CloneSection);
});
function CloneSection() {
$("body").append($(".Entries:first").clone(true));
}
</script>
<body>
<div class="Entries" name="Entries">
<legend class="leftmargin"> Entry </legend>
<form class="form">
<fieldset>
<div class="forminput">
<label for="channel-description" class="formtextarea">Description</label>
<textarea class="channeldescription" name="channeldescription" type="text"></textarea>
</div>
<div class="forminput">
<label for="channel-record_number">Record number</label>
<input class="channelrecordnumber" name="channelrecordnumber"/>
</div>
<div class="forminput">
<label for="channel-hex_color">Hex color</label>
<input class="channelhexcolor" name="channelhexcolor"/>
</div>
<div class="forminput">
<label for="channel-bam_link">BAM file Repsitory Link</label>
<input class="channelbamlink" name="channelbamlink" type="text" data-help-text="bam_link"/>
</div>
</fieldset>
</form>
</div>
</body>
<div id="Cloning" class="button_fixed">
<p>
<button id="CloneForm">Add another entry</button>
<button id="SubmitButton">Generate XM</button>
</p>
</div>
<div id="generated" style="display:none">
<h2>bamdata.xml</h2>
Download XML
<textarea id="ResultXml" style="width: 100%; height: 30em" readonly="readonly"></textarea>
</div>
</div>
</html>
demo:http://www.w3schools.com/code/tryit.asp?filename=F0TXIUR1CYE4
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
Does anyone have an example of a quiz made with jQuery, without server-side processing of the results? After answering the questions, the result appears instantly. :)
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
$(document).ready(function(){
var a = $(".question");
a.each(function(index) {
var flip = $(this).find(".flip");
var panel = $(this).find(".panel");
flip.click(function(){
panel.slideDown("slow");
});
});
});
div.panel,div.flip
{
margin:0px;
padding:5px;
text-align:center;
background:#e5eecc;
border:solid 1px #c3c3c3;
width:140px;
}
div.panel
{
display:none;
}
div.question
{
float:left;
}
div.questions
{
height: 80px;
}
Here's an example makes it reasonably easy to add more questions once the initial javascript is in:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<title>Javascript sample</title>
</head>
<body>
<p>1) How many bits are in a byte?</p>
<div class="questions">
<div class="question">
<div class="panel">Wrong</div>
<div class="flip">7</div>
</div>
<div class="question">
<div class="panel">Right</div>
<div class="flip">8</div>
</div>
</div>
</body>
</html>
This is kind of what #gov was talking about but basically I would just capture the submit of the form:
<form id="myform" onsubmit="return mySubmitHandler()">
Then have a function to handle the submission:
function mySubmitHandler()
{
// the following are just examples of what you could do
var q1val = jQuery('#q1').val();
var q2val = jQuery('#q2').val();
if(q1val + q2val > 5)
jQuery('#success').show();
else
jQuery('#fail').show();
// end example
return false; // this keeps the form from doing a postback
}
$(document).ready(function(){
var items = [
['male'],
['bus','bike'],
['painting','cricket'],
['hocky'],
['female'],
['bus','bike','car'],
['painting','sketches','pool'],
['cricket']
];
var totalQuestion = items.length;
var correctAns = -1;
var i = 0;
var j = 0;
$('.checkBtn').on('click',function(){
$('.block').each(function(){
$(this).children('input').each(function(){
if($(this).is(':checked'))
{
if(items[i][j] == $(this).val()){
$(this).parent().removeClass('incorrect');
$(this).parent().addClass('correct');
if(j < items[i].length - 1){
j++;
}
}else{
$(this).parent().removeClass('correct');
$(this).parent().addClass('incorrect');
return false;
}
}else{
if(items[i][j] == $(this).val()){
$(this).parent().removeClass('correct');
$(this).parent().addClass('incorrect');
}
}
});
i++;
j=0;
});
$('.answer').html($('.correct').length + " / " + totalQuestion);
});
});
.block{
padding:10px 15px;
margin-bottom:15px;
border:2px solid #dadada;
border-radius:5px;
}
.correct{
border:2px solid green;
}
.incorrect{
border:2px solid red;
}
input{
padding:10px;
border:1px solid #dadada;
}
span{
padding:2px 10px;
display:inline-block;
}
<!DOCTYPE html>
<html>
<title>HTML Tutorial</title>
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" ></script>
<body>
<div class="container">
<br/>
<h4 class="answer"></h4>
<div id="que1" class="block">
<h2>Gender?</h2>
<input type="radio" name="gender" value="male"><span>male</span> <br>
<input type="radio" name="gender" value="female"><span>female</span>
</div>
<div id="que2" class="block">
<h2>Vehicle?</h2>
<input type="checkbox" value="bus"><span>bus</span> <br>
<input type="checkbox" value="bike"><span>bike</span> <br>
<input type="checkbox" value="car"><span>car</span>
</div>
<div id="que3" class="block">
<h2>Hobby?</h2>
<input type="checkbox" value="painting"><span>painting</span> <br>
<input type="checkbox" value="sketches"><span>sketches</span> <br>
<input type="checkbox" value="pool"><span>pool</span> <br>
<input type="checkbox" value="cricket"><span>cricket</span>
</div>
<div id="que5" class="block">
<h2>National Game?</h2>
<input type="radio" name="game" value="cricket"><span>cricket</span> <br>
<input type="radio" name="game" value="hocky"><span>hocky</span>
</div>
<div id="que6" class="block">
<h2>Gender?</h2>
<input type="radio" name="gender2" value="male"><span>male</span> <br>
<input type="radio" name="gender2" value="female"><span>female</span>
</div>
<div id="que7" class="block">
<h2>Vehicle?</h2>
<input type="checkbox" value="bus"><span>bus</span> <br>
<input type="checkbox" value="bike"><span>bike</span> <br>
<input type="checkbox" value="car"><span>car</span>
</div>
<div id="que8" class="block">
<h2>Hobby?</h2>
<input type="checkbox" value="painting"><span>painting</span> <br>
<input type="checkbox" value="sketches"><span>sketches</span> <br>
<input type="checkbox" value="pool"><span>pool</span>
</div>
<div id="que9" class="block">
<h2>National Game?</h2>
<input type="radio" name="game2" value="cricket"><span>cricket</span> <br>
<input type="radio" name="game2" value="hocky"><span>hocky</span>
</div>
<br/>
Submit
</div>
</body>
</html>