Making button enabled when javascript return true - javascript

I'm trying to do a form with a basic captcha. Currently, because I'm a novice HTML coder, I only did the submit button enabled when the user clicks the verify button (it doesn'T enable itself when it sees return true.) And I'm trying to make it so if it returns return true i want to make the button enabled, and disabled at other times. Here is the link to the code: https://codepen.io/pen/GRpVmve
I would appreciate if anyone helps.

remove button verify button and add to input oninput function
function Check(){
document.getElementById("button2").disabled = true;
if(ValidCaptcha()){
document.getElementById("button2").disabled = false;
}
}
function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var i;
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").value = code;
Check()
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
return true;
}
else{
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
<form action="https://www.w3schools.com/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<h3>Gender</h3>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<body onload="Captcha();">
<table>
<tr>
<h3>
Captcha<br />
</td>
</tr>
<tr>
<td>
<input type="text" id="mainCaptcha" disabled/>
<input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
</td>
</tr>
<tr>
<td>
<input type="text"oninput="Check()" name="captcha" id="txtInput"/>
</td>
</tr>
<tr>
<td>
<input type="submit" id="button2" value="Send" disabled>
</td>
</tr>
</table>
</body>
</form>

I think this will work for you...
window.onload=()=>{
document.getElementById('button2').disabled = true;
let text = document.getElementById('txtInput').value;
Captcha();
}
function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").value = code
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
document.getElementById('button2').disabled = false;
}
else{
document.getElementById('button2').disabled = true;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
function check(x){
if(x.length<7 || x.length>7){
document.getElementById('button2').disabled = true;
}
}
<form action="https://www.w3schools.com/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<h3>Gender</h3>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<body onload="Captcha();">
<table>
<tr>
<h3>
Captcha<br />
</td>
</tr>
<tr>
<td>
<input type="text" id="mainCaptcha" disabled/>
<input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
</td>
</tr>
<tr>
<td>
<input type="text" id="txtInput" onkeyup="check(this.value)"/>
</td>
</tr>
<tr>
<td>
<input id="button1" type="button" value="Verify" onclick="ValidCaptcha()">
<input type="submit" id="button2" value="Send">
</td>
</tr>
</table>
</body>
</form>

Related

Don't calculate if a field is empty (Js calculator)

I'm trying to limit a calculation only when a field is blank. I have many other fields that are calculated simultaneously, I would like to limit the calculation to only the fields that have not been filled.
I don't know JS very well, so I hope to be able to find help here ... Thanks for any answers, I leave more info below.
Basically everything works fine. However, when the bodyfat field is empty, the calculation for BMR and TDEE Katch McArdle and Cunningham Formula is performed.
What I am trying to do is to calculate the McArdle and Cunningham Formula fields only when the Bodyfat field contains values.
calculate = function()
{
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
var age = document.getElementById('age').value;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
https://jsfiddle.net/snake93/4n9dgbfw/3/
I have added a if condition for checking body fat Now it will works fine.
calculate = function()
{
var weight = document.getElementById('weight').value || 0;
var height = document.getElementById('height').value || 0;
var age = document.getElementById('age').value || 0;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value || "Male" ;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
if(bodyfat!=""){
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
}
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
.mts-field {
width:100%;
text-align: right;
border-bottom: 2px solid #DCDCDE !important;
background: #fff;
}
<label id="prov" class="mts-label">Peso</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="weight" name="weight1" placeholder="es: 70Kg" form="bmrcalc" required/>
<label class="mts-label">Altezza</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="height" name="height1" placeholder="es: 170cm" form="bmrcalc" required/>
<label class="mts-label">Età</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="age" name="age1" placeholder="es: 25 anni" form="bmrcalc" required/>
<label class="mts-label">Bodyfat in %</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="bodyfat" name"bodyfat1" placeholder="es: 15%" form="bmrcalc" />
<div class="mts-label">Sesso</div>
<!--Radio Button Sex-->
<div class="mts-radio-button">
<input type="radio" id="sexuomo" name="radios" value="Male" form="bmrcalc" required>
<label class="mts-label-radio" for="sexuomo">Uomo</label>
</div>
<div class="mts-radio-button1">
<input type="radio" id="sexdonna" name="radios" value="Female" form="bmrcalc" required>
<label class="mts-label-radio" for="sexdonna">Donna</label>
</div>
<!--Select Activity Level-->
<div class="container_level">
<select class="a_level" id="a_level" name="activ_level">
<option value="0">Stile di vita / Attività fisica</option>
<option id="leggeros" name="radiosa" value="1.2">Sedentario (1.2)</option>
<option id="attivos" name="radiosa" value="1.375">Leggero (1.375) </option>
<option id="allenatos" name="radiosa" value="1.55">Moderato (1.55)</option>
<option id="Mattivos" name="radiosa" value="1.75">Attivo (1.75)</option>
<option id="Eattivos" name="radiosa" value="1.9">Estremamente attivo (1.9)</option>
</select>
</div>
<!---BMR Mifflin StJeor Result Field--->
<br>
<label class="mts-label">BMR Mifflin St Jeor Formula</label><br>
<div id="bmr-sexuomo">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_man" name="bmr_mifflin_man"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<br>
<div id="bmr-sexdonna" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_woman" name="bmr_mifflin_woman"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<!---TDEE Mifflin StJeor Result Field--->
<br>
<label class="mts-label">TDEE Mifflin St Jeor Formula</label><br>
<div id="MifflinMale">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_man" name="tdee_mifflin_man"
placeholder="0.000,0 Kcal Uomo" min="1" readonly/>
</div>
<br>
<div id="MifflinFemale" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_woman" name="tdee_mifflin_woman"
placeholder="0.000,0 Kcal donna" min="1" readonly/>
</div>
<!---BMR Katch McArdle Formula--->
<br>
<label class="mts-label">BMR Katch McArdle Formula</label>
<div id="Ktch">
<input type="text" class="mts-field" id="bmr_katch" name="bmr_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Katch McArdle Formula--->
<br>
<label class="mts-label">TDEE Katch McArdle Formula</label>
<div id="Ktch1">
<input type="text" class="mts-field" id="tdee_katch" name="tdee_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---BMR Cunningham Formula--->
<br>
<label class="mts-label">BMR Cunningham Formula</label>
<div id="Cunningham">
<input type="text" class="mts-field" id="bmr_cunningham" name="bmr_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Cunningham Formula--->
<br>
<label class="mts-label">TDEE Cunningham Formula</label>
<div id="Cunninghams">
<input type="text" class="mts-field" id="tdee_cunningham" name="tdee_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---Calc & Reset Button--->
<br>
<form action="" id="bmrcalc">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>
You need to reverse engineer it (think opposite of what you want). For example, think that calling a function when there is something in the textbox is the same as not calling a function when there isn't something in the textbox. So now you have your answer! You just need to add this in your code:
if (document.getElementById('bodyfat').value==""){
preventDefault();
alert("You need to enter something in the textbox first");
}
Thinking like this can help save a lot of time. You didn't need to know anything about Javascript for this, right?

calculate button question, html and javascript

i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />

Why does form not reset (all fields and div of result) after click clear?

I want display div id="showResult" after click calculate button and clear all input and div id="showResult" after click clear button in a form. But clear button doesn't work after I click the button.
What's the problem? How can I solve this problem?
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
You needed to hide the div in the clearForm
Here is your code cleaned up based on the DRY principle (don't repeat yourself)
We could get rid of some testing if we could trust the browser to respect the type="number" which is fairly well supported
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
// the "number" fields will not allow other data than numbers
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161; // add 5 for male, subtract 161 if female
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById("do-form").reset();
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" name="gender" value="male" checked="checked">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
The result div can not auto hide, you need add code to hide it
document.getElementById('showResult').style.visibility = "hidden";
or
document.getElementById('showResult').style.display= "none";
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
//document.getElementById('showResult').style.visibility = "hidden";
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I took some time to improve your code. As given in other answers already. You need to set the display of your result html back to none.
window.onload = function BMR() {
// Init
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
// Click handler
calculate.addEventListener('click', toBmr);
function toBmr() {
// Init
// Very good practice to first declare your vars
// However include result as well here
// Remove select because it's not doing anything
var result = "";
var penalty = 0;
if (gender.value && weight.value && height.value && age.value && gender.checked) {
// When you have duplicate code, check the difference!
// Only the penalty given at the end is different!
if (gender.value == 'male') {
penalty = 5;
} else {
penalty = -161;
}
// Now we calculate with one formula
result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + penalty;
// Add to html
document.getElementById('result').innerHTML = Number(result).toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
};
function clearForm() {
// This resets the form fields
document.getElementById("do-form").reset();
// This remove result again
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>

Writing a code in javascript with radio buttons and using if else loop to calculate simple and/or compound interest

I have been asked to write a code in javascript to show the results in the output boxes based on the input data, the form should like the one shown in the attached image:Interest Calculator
Till now, I have written down the following code; however I am unable to get the results in the output boxes. Could someone please help. Thanks in advance.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").innerHTML = sip;
document.getElementById("a").innerHTML = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").innerHTML = cmp;
document.getElementById("a").innerHTML = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>
innerHTML is used to retrieve or update the content/markup inside a DOM node that can have children. For input elements, you have to use value to get or set the value of the field.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
console.log("simple interest");
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
console.log("compound interest");
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset"><br><br><br>
</form>
Replace innerHTML with value. Because input values are updated using value attribute. Also
the braces here
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
is not required.
function calc() {
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>

How to get Javascript method to print in my HTML

I'm really frustrated trying to get my html and javascript code to work together. I am trying to get the user information from the storeClientData() to print on top of the reservationMessage. I have been working on it for the last 4 hours with no luck. Any help would be much appreciated.
I want to get a output that would show like:
Mr. Firstname, Lastname, street, city, province/state, country, contact info.
Then:
Car size and price, options(ex. navigation), duration in days, cost of rental.
<!DOCTYPE html>
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type = "email" pattern = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onClick="showReservations(); return false;">
<input type = "reset" value = "Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name=type value=25>Small $25.00<br>
<input type=radio name=type value=35>Midsize $35.00<br>
<input type=radio name=type value=45>Full-sized $45.00<br>
<input type=radio name=type value=50 >Van $50.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox name=navigationSystem value= "10" >Navigation System $10.00<br>
<input type=checkbox name=childSeat value="5" >Child Seat $5.00<br>
<input type=checkbox name=roofRack value="15" >Roof Rack $15.00<br>
<input type=checkbox name=bicycleRack value="15" >Bicycle Rack $15.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onClick="calculateRental(); showFinal(); return false;">
</center>
</td>
</tr>
</table>
</div>
<div id="showFinal" style="display:none;">
<h3><span id="reservationResult"; </span></h3>
</div>
</form>
</center>
</body>
</html>
var customerData=[];
function storeClientData(){
var honorific=document.getElementById("honorific").value
customerData[0]=honorific;
var firstName=document.getElementById("firstName").value;
customerData[1]=firstName;
var lastName=document.getElementById("lastName").value;
customerData[2]=lastName;
var street=document.getElementById("street").value;
customerData[3]=street;
var city=document.getElementById("city").value;
customerData[4]=city;
var stateProvince=document.getElementById("stateProvince").value
customerData[5]=stateProvince;
var country=document.getElementById("country").value;
customerData[6]=country;
var businessNumber=document.getElementById("businessNumber").value;
customerData[7]=businessNumber;
var homeNumber=document.getElementById("homeNumber").value;
customerData[8]=homeNumber;
var emailAddress=document.getElementById("emailAddress").value;
customerData[9]=emailAddress;
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]);
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental(){
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x<document.costEstimation.type.length; x++){
if(document.costEstimation.type[x].checked){
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if(document.costEstimation.navigationSystem.checked){
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
}if (document.costEstimation.childSeat.checked){
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
}if (document.costEstimation.roofRack.checked){
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
}if (document.costEstimation.bicycleRack.checked){
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration*carSize)+(duration*extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly=false;
document.getElementById("firstName").readOnly=false;
document.getElementById("lastName").readOnly=false;
document.getElementById("street").disabled=false;
document.getElementById("city").readOnly=false;
document.getElementById("stateProvince").readOnly=false;
document.getElementById("country").disabled=false;
document.getElementById("homeNumber").readOnly=false;
document.getElementById("businessNumber").readOnly=false;
document.getElementById("emailAddress").disabled=false;
}
function showReservations() {
document.getElementById("reservations").style.display = "block";
}
function showFinal() {
document.getElementById("showFinal").style.display = "block";
}
var customerData = [];
function storeClientData() {
var honorific = document.getElementById("honorific").value
customerData[0] = honorific;
var firstName = document.getElementById("firstName").value;
customerData[1] = firstName;
var lastName = document.getElementById("lastName").value;
customerData[2] = lastName;
var street = document.getElementById("street").value;
customerData[3] = street;
var city = document.getElementById("city").value;
customerData[4] = city;
var stateProvince = document.getElementById("stateProvince").value
customerData[5] = stateProvince;
var country = document.getElementById("country").value;
customerData[6] = country;
var businessNumber = document.getElementById("businessNumber").value;
customerData[7] = businessNumber;
var homeNumber = document.getElementById("homeNumber").value;
customerData[8] = homeNumber;
var emailAddress = document.getElementById("emailAddress").value;
customerData[9] = emailAddress;
var CarSize = document.querySelector('input[name="type"]:checked').value;
customerData[10] = CarSize;
var prices = document.getElementsByClassName('addtionClass');
var str = "";
for (var i = 0; i < prices.length; i++) {
if (prices[i].checked)
{
str += prices[i].value + ",";
}
}
customerData[11] = str;
var duration = document.getElementById('duration').value;
customerData[12] = duration;
duration = parseFloat(duration)
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]
+ "<br>" + customerData[10]
+ "<br>" + customerData[11]
+ "<br>" + customerData[12]
);
calculateRental();
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental() {
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x < document.costEstimation.type.length; x++) {
if (document.costEstimation.type[x].checked) {
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if (document.costEstimation.navigationSystem.checked) {
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
} if (document.costEstimation.childSeat.checked) {
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
} if (document.costEstimation.roofRack.checked) {
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
} if (document.costEstimation.bicycleRack.checked) {
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration * carSize) + (duration * extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly = false;
document.getElementById("firstName").readOnly = false;
document.getElementById("lastName").readOnly = false;
document.getElementById("street").disabled = false;
document.getElementById("city").readOnly = false;
document.getElementById("stateProvince").readOnly = false;
document.getElementById("country").disabled = false;
document.getElementById("homeNumber").readOnly = false;
document.getElementById("businessNumber").readOnly = false;
document.getElementById("emailAddress").disabled = false;
}
debugger;
function showReservations() {
document.getElementById('reservations').style.display = 'block';
}
function showFinal() {
document.getElementById('showFinalResult').style.display = 'block';
}
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<input type="button" value="Print HTML" onclick="storeClientData(); return false;" />
<div id="customerResult">
</div>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onclick="showReservations(); return false;">
<input type="reset" value="Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name="type" value=25>Small $25.00<br>
<input type=radio name="type" value=35>Midsize $35.00<br>
<input type=radio name= "type" value=45>Full-sized $45.00<br>
<input type=radio name="type" value=50>Van $50.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox class="addtionClass" name=navigationSystem value="10">Navigation System $10.00<br>
<input type=checkbox class="addtionClass" name=childSeat value="5">Child Seat $5.00<br>
<input type=checkbox class="addtionClass" name=roofRack value="15">Roof Rack $15.00<br>
<input type=checkbox class="addtionClass" name=bicycleRack value="15">Bicycle Rack $15.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onclick="calculateRental(); showFinal(); return false;">
</center>
</table>
</div>
<div id="showFinalResult" style="display:none;">
<h3><span id="reservationResult" > </span></h3>
</div>
</form>
</center>
</body>
</html>
You didn't add id="customerResult" attribute in HTML and also you didn't invoke storeClientData() function from HTML. That's the reason why you couldn't get user information from storeClientData() function and couldn't print it top of the reservation form.
I added <input type=button value="storeClientData" onClick="storeClientData(); return false;"> element before registeration button element in HTML and <div id="customerResult"></div> element top of the reservation form.
You can refer final code in jsfiddle link http://jsfiddle.net/ADukg/10171/.

Categories

Resources