Why the dom element not updating it's innerHTML? - javascript

The dom element stays the same even if I change the height or weight to make bmi underweight. How can I make the p element change dynamically when the BMI changes?
Here is the JS:
let heightEl = document.getElementById("height");
let weightEl = document.getElementById("weight");
let bmidisplayEl = document.getElementById("bmi-value");
let bmisubmitEl = document.getElementById("bmi-submit");
bmisubmitEl.addEventListener("click",bmiCalc);
export default function bmiCalc(){
let heightSquare =Math.pow(Number(heightEl.value), 2);
let bmiResult = Math.floor(Number(weightEl.value)*703/heightSquare);
let bmiStatus = document.createElement("p");
bmiStatus.setAttribute("id","bmistatus");
bmidisplayEl.innerHTML =`Your bmi is ${bmiResult}`;
if (bmiResult <= 18.5){
bmiStatus.innerHTML=`Underweight`;
}else if(bmiResult =>25){
bmiStatus.innerHTML=`Overweight`;
}
else{
bmiStatus.innerHTML=`Healthy`;
}
const bmiBody = document.getElementById("bmi");
bmiBody.appendChild(bmiStatus);
}
and here is the html:
<div id="bmi">
<h1>BMI Calculator</h1>
<div id="bmi-form-container">
<form action="" onsubmit="event.preventDefault()" >
<div id="top-row">
<div id="gender">
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br>
</div>
<div id="bmi-age">
<label for="">Age</label>
<input type="text" placeholder="" required>
</div>
</div>
<div id="form-inputs">
<label for="">Height(inches)</label><br>
<input type="text" placeholder="height" id="height" required>
<label for="">Weight(lb)</label>
<input type="text" placeholder="weight" id="weight" required>
</div>
<button id="bmi-submit">Submit</button>
</form>
</div>
<p id="bmi-value"></p>
</div>
Could it be the form submission issue as well?
I want it to display the proper bmi status as the bmi value changes. Instead, it never update the innerHTML after the first submission.

You need to check if the "bmistatus" p exist, if not then we create a new p, else we editing the existing one
let heightEl = document.getElementById("height");
let weightEl = document.getElementById("weight");
let bmidisplayEl = document.getElementById("bmi-value");
let bmisubmitEl = document.getElementById("bmi-submit");
bmisubmitEl.addEventListener("click",bmiCalc);
function bmiCalc(){
let heightSquare =Math.pow(Number(heightEl.value), 2);
let bmiResult = Math.floor(Number(weightEl.value)*703/heightSquare);
//get the bmistatus p element
let bmiStatus = document.querySelector("#bmistatus");
//if no bmiStatus element is found, then we create a new p
if (bmiStatus == undefined){
bmiStatus = document.createElement("p");
bmiStatus.setAttribute("id","bmistatus");
let bmiBody = document.getElementById("bmi");
bmiBody.appendChild(bmiStatus);
}
bmidisplayEl.innerHTML =`Your bmi is ${bmiResult}`;
if (bmiResult <= 18.5){
bmiStatus.innerHTML=`Underweight`;
}else if(bmiResult >= 25){
bmiStatus.innerHTML=`Overweight`;
}
else{
bmiStatus.innerHTML=`Healthy`;
}
}
<div id="bmi">
<h1>BMI Calculator</h1>
<div id="bmi-form-container">
<form action="" onsubmit="event.preventDefault()">
<div id="top-row">
<div id="gender">
<p>Please select your gender:</p>
<input type="radio" id="male" name="gender" value="Male" required>
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label><br>
</div>
<div id="bmi-age">
<label for="age">Age</label>
<input type="text" placeholder="" id="age" required>
</div>
</div>
<div id="form-inputs">
<label for="height">Height(inches)</label><br>
<input type="text" placeholder="height" id="height" required>
<label for="weight">Weight(lb)</label>
<input type="text" placeholder="weight" id="weight" required>
</div>
<button id="bmi-submit">Submit</button>
</form>
</div>
<p id="bmi-value"></p>
</div>
Edit : I add a gif where we see that the bmiStatus changes as expected

Related

Why do I get this reference error for an undefined variable when I run this js function

Here is my HTML:
<head>
<link rel="stylesheet" href="form.css">
<script type="text/javascript" src="form.js"></script>
</head>
<body>
<div id="wrapper">
<center>
<h1 hidden id="result">If you are traveling in <span class="input" id="countryt">(ctry)</span> and find yourself having to cross a piranha-filled river, here's how to do it <span class="input" id="adverbGroup1t">(adv1)</span>: Pirahnas are more <span class="input" id="adjectiveGroup1t">(adj1)</span> during the day, so cross the river at night. Avoid areas with netted <span class="input" id="animalt">(anml)</span> traps, piranhas may be <span class="input" id="verbGroup1t">(vrb1)</span> there looking to <span class="input" id="verbGroup2t">(vrb2)</span> you! When <span class="input" id="verbGroup3t"></span>(vrb3) the river, swim <span class="input" id="adverbGroup2t">(adv2)</span>. You don't want to wake them up and make them <span class="input" id="adjectiveGroup2t">(adj2)</span>! Whatever you do, if you have an open wound, try to find another way to get back to <span class="input" id="country2t">(ctry2)</span>. Pirahnas are attracted to fresh <span class="input" id="liquidt">(lqd)</span> and will most likely take a bite out of your <span class="input" id="bodyPartt">(bp)</span> if you <span class="input" id="verbGroup4t">(vrb4)</span> the water!</h1>
<h1 id="headText">Fill In The Form</h1>
<!-- <form action="form.php" method="post"> -->
<div id="form-elements"></div>
<form onsubmit="submitted()" id="form">
<p>A Country:</p>
<input autocomplete="off" type="text" name="country2Input" id="country">
<p>=============================</p>
<p>An Adverb:</p>
<input type="radio" value="awfully" id="awfully" name="adverbGroup1">
<label for="awfully">awfully</label>
<input type="radio" value="slowly" id="slowly" name="adverbGroup1">
<label for="slowly">slowly</label>
<input type="radio" value="clumsily" id="clumsily" name="adverbGroup1">
<label for="clumsily">clumsily</label>
<p>=============================</p>
<p>An Adjective:</p>
<input type="radio" value="amused" id="amused" name="adjectiveGroup1">
<label for="amused">amused</label>
<input type="radio" value="adventerous" id="adventerous" name="adjectiveGroup1">
<label for="adventerous">adventerous</label>
<input type="radio" value="little" id="little" name="adjectiveGroup1">
<label for="little">little</label>
<p>=============================</p>
<p>An Animal:</p>
<input autocomplete="off" type="text"name="animalInput" id="animal">
<p>=============================</p>
<p>A Verb:</p>
<input type="radio" value="running" value="" id="running" name="verbGroup1">
<label for="running">running</label>
<input type="radio" value="dancing" value="" id="dancing" name="verbGroup1">
<label for="dancing">dancing</label>
<input type="radio" value="thinking" value="" id="thinking" name="verbGroup1">
<label for="thinking">thinking</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="leave" value="" id="leave" name="verbGroup2">
<label for="leave">leave</label>
<input type="radio" value="bend" value="" id="bend" name="verbGroup2">
<label for="bend">bend</label>
<input type="radio" value="watch" value="" id="watch" name="verbGroup2">
<label for="watch">watch</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="capturing" id="capturing" name="verbGroup3">
<label for="capturing">capturing</label>
<input type="radio" value="drinking" id="drinking" name="verbGroup3">
<label for="drinking">drinking</label>
<input type="radio" value="creating" id="creating" name="verbGroup3">
<label for="creating">creating</label>
<p>=============================</p>
<p>Another Adverb:</p>
<input type="radio" value="carelessly" id="carelessly" name="adverbGroup2">
<label for="carelessly">carelessly</label>
<input type="radio" value="rapidly" id="rapidly" name="adverbGroup2">
<label for="rapidly">rapidly</label>
<input type="radio" value="greedily" id="greedily" name="adverbGroup2">
<label for="greedily">greedily</label>
<p>=============================</p>
<p>Another Adjective:</p>
<input type="radio" value="invisible" id="invisible" name="adjectiveGroup2">
<label for="invisible">invisible</label>
<input type="radio" value="insane" id="insane" name="adjectiveGroup2">
<label for="insane">insane</label>
<input type="radio" value="confused" id="confused" name="adjectiveGroup2">
<label for="confused">confused</label>
<p>=============================</p>
<p>Another Country:</p>
<input autocomplete="off" type="text" name="countryInput" id="country2">
<p>=============================</p>
<p>A type of liquid:</p>
<input type="radio" value="gasoline" id="gasoline" name="liquid">
<label for="gasoline">gasoline</label>
<input type="radio" value="water" id="water" name="liquid">
<label for="water">water</label>
<input type="radio" value="coffee" id="coffee" name="liquid">
<label for="coffee">coffee</label>
<p>=============================</p>
<p>Body Part:</p>
<input type="radio" value="toes" id="toes" name="bodyPart">
<label for="toes">toes</label>
<input type="radio" value="fingers" id="fingers" name="bodyPart">
<label for="fingers">fingers</label>
<input type="radio" value="face" id="face" name="bodyPart">
<label for="face">face</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="clean" id="clean" name="verbGroup4">
<label for="clean">clean</label>
<input type="radio" value="watch" id="watch2" name="verbGroup4">
<label for="watch2">watch</label>
<input type="radio" value="escape" id="escape" name="verbGroup4">
<label for="escape">escape</label>
<br>
<br>
</form>
<button onclick="submitted()" id="sub" >Submit</button>
<button hidden onclick="show()" id="show">Show result</button>
</div>
</center>
</div>
</body>
</html>
And here is my JS
function submitted() {
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
var countryvalue = document.getElementById("country").value
console.log(countryvalue)
//divider
const adverbGroup1s = document.querySelectorAll('input[name="adverbGroup1"]');
let adverbGroup1value;
for (const adverbGroup1 of adverbGroup1s) {
if (adverbGroup1.checked) {
adverbGroup1value = adverbGroup1.value;
console.log(adverbGroup1value)
break;
}
}
//divider
const adjectiveGroup1s = document.querySelectorAll('input[name="adjectiveGroup1"]');
let adjectiveGroup1value;
for (const adjectiveGroup1 of adjectiveGroup1s) {
if (adjectiveGroup1.checked) {
adjectiveGroup1value = adjectiveGroup1.value;
console.log(adjectiveGroup1value)
break;
}
}
//divider
var animalvalue = document.getElementById("animal").value
console.log(animalvalue)
//divider
const verbGroup1s = document.querySelectorAll('input[name="verbGroup1"]');
let verbGroup1value;
for (const verbGroup1 of verbGroup1s) {
if (verbGroup1.checked) {
verbGroup1value = verbGroup1.value;
console.log(verbGroup1value)
break;
}
}
//divider
const verbGroup2s = document.querySelectorAll('input[name="verbGroup2"]');
let verbGroup2value;
for (const verbGroup2 of verbGroup2s) {
if (verbGroup2.checked) {
verbGroup2value = verbGroup2.value;
console.log(verbGroup2value)
break;
}
}
//divider
const verbGroup3s = document.querySelectorAll('input[name="verbGroup3"]');
let verbGroup3value;
for (const verbGroup3 of verbGroup3s) {
if (verbGroup3.checked) {
verbGroup3value = verbGroup3.value;
console.log(verbGroup3value)
break;
}
}
//divider
const adverbGroup2s = document.querySelectorAll('input[name="adverbGroup2"]');
let adverbGroup2value;
for (const adverbGroup2 of adverbGroup2s) {
if (adverbGroup2.checked) {
adverbGroup2value = adverbGroup2.value;
console.log(adverbGroup2value)
break;
}
}
//divider
const adjectiveGroup2s = document.querySelectorAll('input[name="adjectiveGroup2"]');
let adjectiveGroup2value;
for (const adjectiveGroup2 of adjectiveGroup2s) {
if (adjectiveGroup2.checked) {
adjectiveGroup2value = adjectiveGroup2.value;
console.log(adjectiveGroup2value)
break;
}
}
//divider
var country2value = document.getElementById("country2").value
console.log(country2value)
//divider
const liquids = document.querySelectorAll('input[name="liquid"]');
let liquidvalue;
for (const liquid of liquids) {
if (liquid.checked) {
liquidvalue = liquid.value;
console.log(liquidvalue)
break;
}
}
//divider
const bodyParts = document.querySelectorAll('input[name="bodyPart"]');
let bodyPartvalue;
for (const bodyPart of bodyParts) {
if (bodyPart.checked) {
bodyPartvalue = bodyPart.value;
console.log(bodyPartvalue)
break;
}
}
//divider
const verbGroup4s = document.querySelectorAll('input[name="verbGroup4"]');
let verbGroup4value;
for (const verbGroup4 of verbGroup4s) {
if (verbGroup4.checked) {
verbGroup4value = verbGroup4.value;
console.log(verbGroup4value)
break;
}
}
document.getElementById("form").reset();
document.getElementById("show").hidden = false
});
}
function show() {
document.getElementById("form").hidden = true
document.getElementById("sub").hidden = true
document.getElementById("show").hidden = true
document.getElementById("headText").hidden = true
document.getElementById("result").hidden = false
document.getElementById("countryt").innerHTML = countryvalue
document.getElementById("adverbGroup1t").innerHTML = adverbGroup1value
document.getElementById("adjectiveGroup1t").innerHTML = adjectiveGroup1value
document.getElementById("animalt").innerHTML = animalvalue
document.getElementById("verbGroup1t").innerHTML = verbGroup1value
document.getElementById("verbGroup2t").innerHTML = verbGroup2value
document.getElementById("verbGroup3t").innerHTML = verbGroup3value
document.getElementById("adverbGroup2t").innerHTML = adverbGroup2value
document.getElementById("adjectiveGroup2t").innerHTML = adjectiveGroup2value
document.getElementById("country2t").innerHTML = country2value
document.getElementById("liquidt").innerHTML = liquidvalue
document.getElementById("bodyPartt").innerHTML = bodyPartvalue
document.getElementById("verbGroup4t").innerHTML = verbGroup4value
}
When I run this, I expect all of the content inside each span tag to be replaced with its correct strings which are stored in the variables which end with "value"
However, whenever I run this, I get this error:
"Uncaught ReferenceError: countryvalue is not defined at show (form.js:174:53) at HTMLButtonElement.onclick ((index):110:47)"
How do I make this work as I explained earlier
hi bro
You should put your script file at the end of the html file and make sure that the file address is correct.
function submitted() {
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
var countryvalue = document.getElementById("country").value
console.log(countryvalue)
//divider
const adverbGroup1s = document.querySelectorAll('input[name="adverbGroup1"]');
let adverbGroup1value;
for (const adverbGroup1 of adverbGroup1s) {
if (adverbGroup1.checked) {
adverbGroup1value = adverbGroup1.value;
console.log(adverbGroup1value)
break;
}
}
//divider
const adjectiveGroup1s = document.querySelectorAll('input[name="adjectiveGroup1"]');
let adjectiveGroup1value;
for (const adjectiveGroup1 of adjectiveGroup1s) {
if (adjectiveGroup1.checked) {
adjectiveGroup1value = adjectiveGroup1.value;
console.log(adjectiveGroup1value)
break;
}
}
//divider
var animalvalue = document.getElementById("animal").value
console.log(animalvalue)
//divider
const verbGroup1s = document.querySelectorAll('input[name="verbGroup1"]');
let verbGroup1value;
for (const verbGroup1 of verbGroup1s) {
if (verbGroup1.checked) {
verbGroup1value = verbGroup1.value;
console.log(verbGroup1value)
break;
}
}
//divider
const verbGroup2s = document.querySelectorAll('input[name="verbGroup2"]');
let verbGroup2value;
for (const verbGroup2 of verbGroup2s) {
if (verbGroup2.checked) {
verbGroup2value = verbGroup2.value;
console.log(verbGroup2value)
break;
}
}
//divider
const verbGroup3s = document.querySelectorAll('input[name="verbGroup3"]');
let verbGroup3value;
for (const verbGroup3 of verbGroup3s) {
if (verbGroup3.checked) {
verbGroup3value = verbGroup3.value;
console.log(verbGroup3value)
break;
}
}
//divider
const adverbGroup2s = document.querySelectorAll('input[name="adverbGroup2"]');
let adverbGroup2value;
for (const adverbGroup2 of adverbGroup2s) {
if (adverbGroup2.checked) {
adverbGroup2value = adverbGroup2.value;
console.log(adverbGroup2value)
break;
}
}
//divider
const adjectiveGroup2s = document.querySelectorAll('input[name="adjectiveGroup2"]');
let adjectiveGroup2value;
for (const adjectiveGroup2 of adjectiveGroup2s) {
if (adjectiveGroup2.checked) {
adjectiveGroup2value = adjectiveGroup2.value;
console.log(adjectiveGroup2value)
break;
}
}
//divider
var country2value = document.getElementById("country2").value
console.log(country2value)
//divider
const liquids = document.querySelectorAll('input[name="liquid"]');
let liquidvalue;
for (const liquid of liquids) {
if (liquid.checked) {
liquidvalue = liquid.value;
console.log(liquidvalue)
break;
}
}
//divider
const bodyParts = document.querySelectorAll('input[name="bodyPart"]');
let bodyPartvalue;
for (const bodyPart of bodyParts) {
if (bodyPart.checked) {
bodyPartvalue = bodyPart.value;
console.log(bodyPartvalue)
break;
}
}
//divider
const verbGroup4s = document.querySelectorAll('input[name="verbGroup4"]');
let verbGroup4value;
for (const verbGroup4 of verbGroup4s) {
if (verbGroup4.checked) {
verbGroup4value = verbGroup4.value;
console.log(verbGroup4value)
break;
}
}
document.getElementById("form").reset();
document.getElementById("show").hidden = false
});
}
function show() {
document.getElementById("form").hidden = true
document.getElementById("sub").hidden = true
document.getElementById("show").hidden = true
document.getElementById("headText").hidden = true
document.getElementById("result").hidden = false
document.getElementById("countryt").innerHTML = countryvalue
document.getElementById("adverbGroup1t").innerHTML = adverbGroup1value
document.getElementById("adjectiveGroup1t").innerHTML = adjectiveGroup1value
document.getElementById("animalt").innerHTML = animalvalue
document.getElementById("verbGroup1t").innerHTML = verbGroup1value
document.getElementById("verbGroup2t").innerHTML = verbGroup2value
document.getElementById("verbGroup3t").innerHTML = verbGroup3value
document.getElementById("adverbGroup2t").innerHTML = adverbGroup2value
document.getElementById("adjectiveGroup2t").innerHTML = adjectiveGroup2value
document.getElementById("country2t").innerHTML = country2value
document.getElementById("liquidt").innerHTML = liquidvalue
document.getElementById("bodyPartt").innerHTML = bodyPartvalue
document.getElementById("verbGroup4t").innerHTML = verbGroup4value
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="form.css">
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div id="wrapper">
<center>
<h1 hidden id="result">If you are traveling in <span class="input" id="countryt">(ctry)</span> and find yourself having to cross a piranha-filled river, here's how to do it <span class="input" id="adverbGroup1t">(adv1)</span>: Pirahnas are more <span class="input" id="adjectiveGroup1t">(adj1)</span> during the day, so cross the river at night. Avoid areas with netted <span class="input" id="animalt">(anml)</span> traps, piranhas may be <span class="input" id="verbGroup1t">(vrb1)</span> there looking to <span class="input" id="verbGroup2t">(vrb2)</span> you! When <span class="input" id="verbGroup3t"></span>(vrb3) the river, swim <span class="input" id="adverbGroup2t">(adv2)</span>. You don't want to wake them up and make them <span class="input" id="adjectiveGroup2t">(adj2)</span>! Whatever you do, if you have an open wound, try to find another way to get back to <span class="input" id="country2t">(ctry2)</span>. Pirahnas are attracted to fresh <span class="input" id="liquidt">(lqd)</span> and will most likely take a bite out of your <span class="input" id="bodyPartt">(bp)</span> if you <span class="input" id="verbGroup4t">(vrb4)</span> the water!</h1>
<h1 id="headText">Fill In The Form</h1>
<!-- <form action="form.php" method="post"> -->
<div id="form-elements"></div>
<form onsubmit="submitted()" id="form">
<p>A Country:</p>
<input autocomplete="off" type="text" name="country2Input" id="country">
<p>=============================</p>
<p>An Adverb:</p>
<input type="radio" value="awfully" id="awfully" name="adverbGroup1">
<label for="awfully">awfully</label>
<input type="radio" value="slowly" id="slowly" name="adverbGroup1">
<label for="slowly">slowly</label>
<input type="radio" value="clumsily" id="clumsily" name="adverbGroup1">
<label for="clumsily">clumsily</label>
<p>=============================</p>
<p>An Adjective:</p>
<input type="radio" value="amused" id="amused" name="adjectiveGroup1">
<label for="amused">amused</label>
<input type="radio" value="adventerous" id="adventerous" name="adjectiveGroup1">
<label for="adventerous">adventerous</label>
<input type="radio" value="little" id="little" name="adjectiveGroup1">
<label for="little">little</label>
<p>=============================</p>
<p>An Animal:</p>
<input autocomplete="off" type="text"name="animalInput" id="animal">
<p>=============================</p>
<p>A Verb:</p>
<input type="radio" value="running" value="" id="running" name="verbGroup1">
<label for="running">running</label>
<input type="radio" value="dancing" value="" id="dancing" name="verbGroup1">
<label for="dancing">dancing</label>
<input type="radio" value="thinking" value="" id="thinking" name="verbGroup1">
<label for="thinking">thinking</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="leave" value="" id="leave" name="verbGroup2">
<label for="leave">leave</label>
<input type="radio" value="bend" value="" id="bend" name="verbGroup2">
<label for="bend">bend</label>
<input type="radio" value="watch" value="" id="watch" name="verbGroup2">
<label for="watch">watch</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="capturing" id="capturing" name="verbGroup3">
<label for="capturing">capturing</label>
<input type="radio" value="drinking" id="drinking" name="verbGroup3">
<label for="drinking">drinking</label>
<input type="radio" value="creating" id="creating" name="verbGroup3">
<label for="creating">creating</label>
<p>=============================</p>
<p>Another Adverb:</p>
<input type="radio" value="carelessly" id="carelessly" name="adverbGroup2">
<label for="carelessly">carelessly</label>
<input type="radio" value="rapidly" id="rapidly" name="adverbGroup2">
<label for="rapidly">rapidly</label>
<input type="radio" value="greedily" id="greedily" name="adverbGroup2">
<label for="greedily">greedily</label>
<p>=============================</p>
<p>Another Adjective:</p>
<input type="radio" value="invisible" id="invisible" name="adjectiveGroup2">
<label for="invisible">invisible</label>
<input type="radio" value="insane" id="insane" name="adjectiveGroup2">
<label for="insane">insane</label>
<input type="radio" value="confused" id="confused" name="adjectiveGroup2">
<label for="confused">confused</label>
<p>=============================</p>
<p>Another Country:</p>
<input autocomplete="off" type="text" name="countryInput" id="country2">
<p>=============================</p>
<p>A type of liquid:</p>
<input type="radio" value="gasoline" id="gasoline" name="liquid">
<label for="gasoline">gasoline</label>
<input type="radio" value="water" id="water" name="liquid">
<label for="water">water</label>
<input type="radio" value="coffee" id="coffee" name="liquid">
<label for="coffee">coffee</label>
<p>=============================</p>
<p>Body Part:</p>
<input type="radio" value="toes" id="toes" name="bodyPart">
<label for="toes">toes</label>
<input type="radio" value="fingers" id="fingers" name="bodyPart">
<label for="fingers">fingers</label>
<input type="radio" value="face" id="face" name="bodyPart">
<label for="face">face</label>
<p>=============================</p>
<p>Another Verb:</p>
<input type="radio" value="clean" id="clean" name="verbGroup4">
<label for="clean">clean</label>
<input type="radio" value="watch" id="watch2" name="verbGroup4">
<label for="watch2">watch</label>
<input type="radio" value="escape" id="escape" name="verbGroup4">
<label for="escape">escape</label>
<br>
<br>
</form>
<button onclick="submitted()" id="sub" >Submit</button>
<button hidden onclick="show()" id="show">Show result</button>
</div>
</center>
</div>
</body>
</html>
</html>
Check the address of this file
<script type="text/javascript" src="app.js"></script>
A few recommendations:
First, to avoid clicking twice on submit button, remove an additional subscription from the submitted function.
So, basically you can remove these lines, from submitted:
const btn = document.querySelector('#sub');
btn.addEventListener("click", () => {
Second, to avoid countryvalue is not defined errors you need to declare your variables out of the submitted function scope, so the variables are visible both in submitte and in show
For example:
let countryvalue;
function submitted() {
countryvalue = document.getElementById("country").value;
}
function show() {
document.getElementById("countryt").innerHTML = countryvalue;
}

Simple value assignment from input box returns NaN

I just assigned the values of the input boxes to variables and now when I want to see the value of the variable from the input box it just shows me, Nan.
var cardamnt = parseFloat(document.getElementById("cardam").value);
var cashamnt = parseFloat(document.getElementById("casham").value);
var giftamnt = parseFloat(document.getElementById("giftcheck").value);
var amnt = parseFloat(document.getElementById("amounttxt").value);
document.getElementById("casham").onchange = function() {
alert(cashamnt);
};
<div class="container">
<h1>Payment Details</h1>
<h3>Amount</h3>
<input type="text" id="amounttxt">
<h3>Payment Type</h3>
<input type="radio" name="radAnswer" id="cashbtn">
<label for="cash">Cash</label><br>
<input type="radio" name="radAnswer" id="cardbtn">
<label for="card">Card</label><br>
<input type="radio" name="radAnswer" id="cashwcardbtn">
<label for="cashwcard">Cash and Card</label></body><br>
<h3>Gift Check</h3>
<input type="text" id="giftcheck">
<h3>Cash Amount</h3>
<input type="text" id="casham">
<h3>Card Amount</h3>
<input type="text" id="cardam"></br>
<button id="sumbitbtn">Submit</button>
</div>
Just take the declaration and push it into onChange, You are reading the value when the JS is execting.
var cashamnt = parseFloat(document.getElementById("casham").value);
Move this line inside onChange and it will work as expected.
var cardamnt = parseFloat(document.getElementById("cardam").value);
var giftamnt = parseFloat(document.getElementById("giftcheck").value);
var amnt = parseFloat(document.getElementById("amounttxt").value);
document.getElementById("casham").onchange = function() {
var cashamnt = parseFloat(document.getElementById("casham").value);
alert(cashamnt);
};
<div class="container">
<h1>Payment Details</h1>
<h3>Amount</h3>
<input type="text" id="amounttxt">
<h3>Payment Type</h3>
<input type="radio" name="radAnswer" id="cashbtn">
<label for="cash">Cash</label><br>
<input type="radio" name="radAnswer" id="cardbtn">
<label for="card">Card</label><br>
<input type="radio" name="radAnswer" id="cashwcardbtn">
<label for="cashwcard">Cash and Card</label></body><br>
<h3>Gift Check</h3>
<input type="text" id="giftcheck">
<h3>Cash Amount</h3>
<input type="text" id="casham">
<h3>Card Amount</h3>
<input type="text" id="cardam"></br>
<button id="sumbitbtn">Submit</button>
</div>

Build a dependence in the behavior of multiple checkboxes and input fields

I have a set of checkboxes for some fruits and vegetables. And I need to write such a function that when at least one of the fruits is selected, the fruit input field appears and does not disappear as long as at least one fruit is selected. When all checkboxes from the fruit are unchecked, the input field should disappear. And the same thing with vegetables.
But I'm confused and can't figure out how to do it better. I would be grateful for your help.
<div>
<input type="checkbox" id="apple" class="custom-checkbox" autocomplete="off" onchange="showInput()">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" id="banana" class="custom-checkbox" autocomplete="off" onchange="showInput()">
<label for="banana">banana</label>
</div>
<div>
<input type="checkbox" id="mangoe" class="custom-checkbox" autocomplete="off" onchange="showInput()">
<label for="mangoe">mangoe</label>
</div>
<div>
<input type="checkbox" id="potato" class="custom-checkbox" autocomplete="off" onchange="showInput()">
<label for="potato">potato</label>
</div>
<div>
<input type="checkbox" id="celery" class="custom-checkbox" autocomplete="off" onchange="showInput()">
<label for="celery">celery</label>
</div>
<input type="text" id="fruits" name="fruits">
<input type="text" id="vegetables" name="vegetables">
function showInput() {}
Check out this code:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<div>
<input type="checkbox" id="apple" class="fruits custom-checkbox" autocomplete="off" onchange="showFruits()">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" id="banana" class="fruits custom-checkbox" autocomplete="off" onchange="showFruits()">
<label for="banana">banana</label>
</div>
<div>
<input type="checkbox" id="mangoe" class="fruits custom-checkbox" autocomplete="off" onchange="showFruits()">
<label for="mangoe">mangoe</label>
</div>
<div>
<input type="checkbox" id="potato" class="vegetables custom-checkbox" autocomplete="off" onchange="showVeggies()">
<label for="potato">potato</label>
</div>
<div>
<input type="checkbox" id="celery" class="vegetables custom-checkbox" autocomplete="off" onchange="showVeggies()">
<label for="celery">celery</label>
</div>
<input type="text" id="text_fruits" name="fruits" disabled>
<input type="text" id="text_vegetables" name="vegetables" disabled>
<button onclick="myFunction()">Click me</button>
<script>
function showFruits() {
var fruits_checklist = document.getElementsByClassName("fruits");
var result = false;
for (var i = 0; i < fruits_checklist.length; i++)
result = result || fruits_checklist[i].checked;
document.getElementById("text_fruits").disabled = !result;
}
function showVeggies() {
var fruits_checklist = document.getElementsByClassName("vegetables");
var result = false;
for (var i = 0; i < fruits_checklist.length; i++)
result = result || fruits_checklist[i].checked;
document.getElementById("text_vegetables").disabled = !result;
}
</script>
</body>
</html>
I added class fruits to all fruits and class vegetables to all vegetables for groupings. Renamed text-feilds to avoid duplicacy. I created separate functions for showing/hiding fruits and vegetables.

Render Price in external Div

I have found a code to display the final price based on some selections from a form imputs (checkbox) affecting the final price. I want also it to affect an external div with text on it. Is a huge fixed element I've created displaying "Final Cost" and I also want this to render the final price by changing the getElementByID and nothing happened. Could you help me to solve this?
I want also .priceText1 also to be affected:)
Actual code is
HTML
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit"/>
<input value="Reset" type="reset"/>
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>
JS
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
}
You could simply use innerText with querySelector to add the total price to the element .priceText1 like :
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
Hope this helps.
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "$" + total.toFixed(2);
document.querySelector(".priceText1").innerText = "$" + total.toFixed(2);
}
<form action="" id="theForm">
<fieldset>
<legend>
Products
</legend>
<label>
<input name="product" value="12.95" type="checkbox" id="p1" onclick="totalIt()"/>
Candy $12.95
</label>
<label>
<input name="product" value="5.99" type="checkbox" id="p2" onclick="totalIt()"/>
Burger $5.99
</label>
<label>
<input name="product" value="1.99" type="checkbox" id="p3" onclick="totalIt()"/>
Coke $1.99
</label>
<label>
Total
<input value="$0.00" readonly="readonly" type="text" id="total"/>
</label>
</fieldset>
<input value="Submit" type="submit" />
<input value="Reset" type="reset" />
</form>
<div class="priceWrapper">
<h3 class="priceText1">$0.00</h3>
<h3 class="priceText2">Final Cost</h3>
</div>

How to change a form using radio buttons?

Using radio button I want to change my form. For example if 'A' radio button is selected, it should show me a form where I can enter my name and age. If 'B' is selected, it should show me another form, where I can see a picture, but the text field for the name and age are no longer visible.
You can use the onchange attribute of an input to call a javascript function, which hides A & shows B or vice versa
function hideA(x) {
if (x.checked) {
document.getElementById("A").style.visibility = "hidden";
document.getElementById("B").style.visibility = "visible";
}
}
function hideB(x) {
if (x.checked) {
document.getElementById("B").style.visibility = "hidden";
document.getElementById("A").style.visibility = "visible";
}
}
Show :
<input type="radio" onchange="hideB(this)" name="aorb" checked>A |
<input type="radio" onchange="hideA(this)" name="aorb">B
<div id="A">
<br/>A's text</div>
<div id="B" style="visibility:hidden">
<br/>B's text</div>
I liked the Answer from Vinayak Garg
Though a more portable solution was desired that could be used for many options using a basic structure minimal javascript is needed to swap options
The example function used in the next 2 snippets is:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production1</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent1</label>
<input type="text" name="d1" value="/">
</p>
</div>
</fieldset>
Doing it this way you can add new options without changing the javascript
such as adding alpha and beta options as shown below you will see the same javascript is used.
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="beta" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="b1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
</fieldset>
It could be even more reusable by adding a second variable to the function:
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this, 'Settings')" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="beta" />
</p>
<p>
<label for="alphaVar">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="alphaVar" checked="checked" />
<label for="betaVar">Beta</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="betaVar" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="d1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
<div id="alphaVarVal">
<br/>Alpha Values
<p>
<label for="aV1">Alpha Vals</label>
<input type="text" name="aV1" value="/">
</p>
</div>
<div id="betaVarVal" style="display:none">
<br/>Beta Values
<p>
<label for="bV1">Beta Vals</label>
<input type="text" name="bV1" value="/">
</p>
</div>
</fieldset>
Javascript for loops are well described in this Answer of the question For-each over an array in JavaScript?
This can be done like this.
<html>
<head>
<script language="Javascript">
function show(x)
{
var element=document.getElementById(x.id);
if(element.id=='a')
{
document.getElementById("area").innerHTML="Name : <input type='text' id='name' >";
}
else
{
document.getElementById("area").innerHTML="<img src='imgSrc' alt='NoImage'>"
}
}
</script>
</head>
<body>
<input type="radio" onclick="show(this)" name="radioButton" id="a" >A
<input type="radio" onclick="show(this)" name="radioButton" id="b" >B
<br> <br> <br>
<div id="area"> </div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div class="row clearfix">
<input type="radio" name="salary_status" id="Hourly" onclick="Hourly()"> Hourly
<input type="radio" name="salary_status" id="Percentage" onclick="Percentage()"> Percentage
</div>
<div class="row clearfix">
<p id="hourly" style="display:none"> <input type="text" placeholder=" Hourly" name="Hourly" placeholder="Hourly" required="required" class="form-control col-md-9 col-xs-12" ></p>
<p id="percentage" style="display:none"> <input type="number" name="Percentage" placeholder="Percentage" required="required" class="form-control col-md-9 col-xs-12" ></p>
</div>
<script>
var text1 = document.getElementById("percentage");
var text = document.getElementById("hourly");
function Hourly() {
var checkBox = document.getElementById("Hourly");
if (checkBox.checked == true){
text.style.display = "block";
text1.style.display = "none";
} else{
text.style.display = "none";
}
}
function Percentage() {
var checkBox = document.getElementById("Percentage");
if (checkBox.checked == true){
text1.style.display = "block";
text.style.display = "none";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>
I modified the above in a more easy way. Try editing it according to your needs:
<html>
<head>
<script language="Javascript">
function hideA()
{
document.getElementById("A").style.visibility="hidden";
document.getElementById("B").style.visibility="visible";
}
function hideB()
{
document.getElementById("B").style.visibility="hidden";
document.getElementById("A").style.visibility="visible";
}
</script>
</head>
<body>Show :
<input type="radio" name="aorb" onClick="hideB()" checked>A |
<input type="radio" name="aorb" onClick="hideA()">B
<div style="position: absolute; left: 10px; top: 100px;" id="A"><br/>A's text</div>
<div style="position: absolute; left: 10px; top: 100px; visibility:hidden" id="B"><br/>B's text</div>
</body>
</html>

Categories

Resources