How to check to make sure a radio button is selected - javascript

I have a form that I need to figure out the code on how to make sure a radio button is selected
Here is the form
<body>
<div id="content">
<p>Enter the values below and click "Calculate".</p>
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="answer">Answer:</label>
<input type="text" id="Answer" disabled="disabled" /><br />
<input type="radio" name="Area" value="Area" check="checked"/>Area<br />
<input type="radio" name="Parimeter" value="Parimeter" />Parimeter<br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</body>
</html>
here is the code
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var length = parseFloat( $("length").value );
var width = parseFloat( $("width").value );
// $("area").value = "";
if (isNaN(length) || length <= 0) {
alert("Length must be a valid number\nand greater than zero.");
} else if(isNaN(width) || width <= 0) {
alert("Width must be a valid number\nand greater than zero.");
}
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area.toFixed(2);
$("perimeter").value = perimeter.toFixed(2);
}
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}

Here are some links that may help you finish your homework:
http://www.w3schools.com/html/html_forms.asp
http://www.w3schools.com/jquery/default.asp
http://jsfiddle.net

Related

How to clear form when radio button is changed

I want to clear form when the radio button is changed. Example gender is male and I fill number in weight input only If I change gender, the form will be clear or when I fill number in all input and click calculate and then BMR show me If I change gender, the form will be clear too.
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
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;
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";
}
const changeGender = () => {
let form = toBmr();
let r = document.getElementById('showResult').style.display;
if (r == "block") {
form = document.querySelector('[name=gender]:checked').addEventListener('change', clearForm());
}
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<div id="selectGender" onchange="changeGender()">
<p>Gender:
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
</p>
</div>
<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>
use form.reset() and then check the button
clearForm = (el) => {
document.querySelector("#f1").reset(); // reset the form
el.checked = true; // since we passed the element into the function we can simply check it
}
<form id="f1">
<input type="text" name="t" /><br />
<input type="radio" id="b1" name="b" value="b1" onclick="clearForm(this)" />
<label for="b1">b1</label><br>
<input type="radio" id="b2" name="b" value="b2" onclick="clearForm(this)" />
<label for="b2">b2</label><br>
</form>

How can I add up my selection lists, radios, and checkboxes to total?

I need some guidance in how to add my selection list to my total. I am still new to javascript so i did what i could but for some reason, i cannot figure out how to add the selection list to my total. the textboxes with 0.00 are there for me to see if the radios, checkboxes and selection are adding up properly.
``
`
function customerInfo(cName){
var dinerName = document.getElementById(cName).value;
document.getElementById('cust_name').innerHTML = dinerName;
}
// format val to n number of decimal places
function formatDecimal(val, n) {
n = n || 2;
var str = "" + Math.round ( parseFloat(val) * Math.pow(10, n) );
while (str.length <= n) {
str = "0" + str;
}
var pt = str.length - n;
return str.slice(0,pt) + "." + str.slice(pt);
}
function getRadioVal(form, name) {
var radios = form.elements[name];
var val;
for (var i=0, len=radios.length; i<len; i++) {
if ( radios[i].checked == true ) {
val = radios[i].value;
break;
}
}
return val;
}
function getToppingsTotal(e) {
var form = this.form;
var val = parseFloat( form.elements['tops_tot'].value );
if ( this.checked == true ) {
val += parseFloat(this.value);
} else {
val -= parseFloat(this.value);
}
form.elements['tops_tot'].value = formatDecimal(val);
updatePizzaTotal(form);
}
function getSizePrice(e) {
this.form.elements['sz_tot'].value = parseFloat( this.value );
updatePizzaTotal(this.form);
}
function getDeliveryPrice(e){
selectElement = document.querySelector('#pick_delivery');
output = selectElement.options[selectElement.selectedIndex].value;
console.log(output);
}
function updatePizzaTotal(form) {
var sz_tot = parseFloat( form.elements['sz_tot'].value );
var tops_tot = parseFloat( form.elements['tops_tot'].value );
form.elements['total'].value = formatDecimal( sz_tot + tops_tot );
}
// removes from global namespace
(function() {
var form = document.getElementById('pizzaForm');
var el = document.getElementById('pizza_toppings');
// input in toppings container element
var tops = el.getElementsByTagName('input');
for (var i=0, len=tops.length; i<len; i++) {
if ( tops[i].type === 'checkbox' ) {
tops[i].onclick = getToppingsTotal;
}
}
var sz = form.elements['size'];
for (var i=0, len=sz.length; i<len; i++) {
sz[i].onclick = getSizePrice;
}
// set sz_tot to value of selected
form.elements['sz_tot'].value = formatDecimal( parseFloat( getRadioVal(form, 'size') ) );
updatePizzaTotal(form);
})(); // end remove from global namespace and invoke
<form name="pizzaOrder" method="post" id="pizzaForm" enctype="text/plain">
<fieldset style="width: 60%;">
<legend>Create Your Pizza</legend>
<h3>Customer's Name:</h3>
<p>
<input type="text" name="client_name" id="client_name" value="First and Last Name" size="30" value="" />
<input type="button" onclick="customerInfo('client_name')" value="Enter"></button>
</p>
<h3>Pick Your Size:</h3>
<p>
<label><input type="radio" name="size" value="8" /> Small</label>
<label><input type="radio" name="size" value="10" /> Medium</label>
<label><input type="radio" name="size" value="12" /> Large</label>
<label><input type="radio" name="size" value="14" checked/> Extra Large</label>
<input type="text" name="sz_tot" value="0.00" />
</p>
<h3>Pick Your Toppings</h3>
<p id="pizza_toppings">
<label><input type="checkbox" name="Pineapple" value="1.50" /> Pineapple</label>
<label><input type="checkbox" name="Onions" value="1.50" /> Onions </label>
<label><input type="checkbox" name="Ham" value="1.50" /> Ham</label>
<label><input type="checkbox" name="Sausage" value="1.50" /> Sausage</label>
<label><input type="checkbox" name="Pepperoni" value="1.50" /> Pepperoni</label>
<input type="text" name="tops_tot" value="0.00" />
</p>
<h3>Delivery Or Pick Up</h3>
<p>
<select class="delivery" id="pick_delivery" size="2">
<option value="0">Pick Up: Free</option>
<option value="2">Delivery: $2</option>
</select>
<input type="button" onclick="getDeliveryPrice()" id="delivery_pick" value="enter" /></button>
</p>
<p>
<label>Total: $ <input type="text" name="total" class="num" value="0.00" readonly="readonly" /></label>
</p>
<p>
<input type="button" value="Confirm" />
<input type="button" value="Cancel">
</p>
</fieldset>
</form>
<div>
<h2>Your Order:</h2>
<p>
<h4>Your Name: <span id="cust_name"> </span></h4>
<h4>Your Pizza Size:</h4>
<h4>Toppings Selected:</h4>
</p>
</div>
</fieldset>
</form>```
On the bottom of the page the results should look similar to this:
Your Name: Pam Love
Pizza Size Selected: Extra Large
Toppings Selected: Bacon, Pineapple, Ham
Total: 20.50
When clicked on confirm order, the onclick button should redirect the page to a new tab that says:
Your order will be ready in 20 minutes.
or if cancelled then the user clicks the cancel button also redirected to a new tab:
Your order is cancelled.
You can just use some css selectors to accomplish most of this.
Here is how you can get your selected size:
document.querySelector('input[type="radio"][name="size"]:checked').value
And here is how you can get the list of toppings:
[...document.querySelectorAll('input[type="checkbox"][name="topping"]:checked')].map((t) => t.value).join(', ')
The remaining things should be pretty easy to find using querySelector or getElementById

I want to show alert message

This is running good, but i want to show alert message if sum of all input value not equal to hundred and stop on same page.
function doMath(){
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
document.write(sum);
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is another solution
function _get(ID){
return document.getElementById(ID);
}
function doMath(){
var my_input1 = _get('my_input1').value ? parseInt(_get('my_input1').value) : 0;
var my_input2 = _get('my_input2').value ? parseInt(_get('my_input2').value) : 0;
var my_input3 = _get('my_input3').value ? parseInt(_get('my_input3').value) : 0;
var my_input4 = _get('my_input4').value ? parseInt(_get('my_input4').value) : 0;
var my_input5 = _get('my_input5').value ? parseInt(_get('my_input5').value) : 0;
var my_input6 = _get('my_input6').value ? parseInt(_get('my_input6').value) : 0;
// Add them together and display
var sum = my_input1 + my_input2 + my_input3 + my_input4 + my_input5 + my_input6;
if(sum==100){
alert('Sum is = 100');
/*YOUR CODE HERE*/
}else if(sum<100){
alert('Sum is less than 100');
/*YOUR CODE HERE*/
}else if(sum>100){
alert('Sum is bigger than 100');
/*YOUR CODE HERE*/
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Here is the details about Conditional (ternary) Operator
If I clearly understood what you want, you can try this:
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if (sum != 100) {
alert('Different from a hundred')
return false;
}
I used return false in case you want to handle the result and take some other action.
You can use alert() function to display alert popup
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
Please refer working snippet
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum!=100){
alert("Sum is not equal to 100");
}else{
document.write(sum);
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />
Replace
document.write(sum);
with
if(sum==100) {
document.write(sum);
} else {
alert("show your messaage");
}
function doMath()
{
// Capture the entered values of two input boxes
var my_input1 = document.getElementById('my_input1').value;
var my_input2 = document.getElementById('my_input2').value;
var my_input3 = document.getElementById('my_input3').value;
var my_input4= document.getElementById('my_input4').value;
var my_input5 = document.getElementById('my_input5').value;
var my_input6 = document.getElementById('my_input6').value;
// Add them together and display
var sum = parseInt(my_input1) + parseInt(my_input2) + parseInt(my_input3) + parseInt(my_input4) + parseInt(my_input5) + parseInt(my_input6);
if(sum >= 100){
document.write(sum);
}
else{
alert("sum is less than 100")
}
}
<input type="text" id="my_input1" /></br>
<input type="text" id="my_input2" /></br>
<input type="text" id="my_input3" /></br>
<input type="text" id="my_input4" /></br>
<input type="text" id="my_input5" /></br>
<input type="text" id="my_input6" />
<input type="button" value="Add Them Together" onclick="doMath();" />

How to display a JavaScript result as a paragraph?

I have been working with a javascript that will calculate BMI of a person. But with the BMI result, I want to display specific comments of specific result group. How can I do that?
Here is the script:
<script>
<!--
function calculateBmi()
{
var weight = document.bmiForm.weight.value
var height = document.bmiForm.height.value
if(weight > 0 && height > 0)
{
var stadnardwight1 = 19*height/100*height/100
document.bmiForm.weight1.value = stadnardwight1
var stadnardwight2 = 25*height/100*height/100
document.bmiForm.weight2.value = stadnardwight2
var finalBmi = weight/(height/100*height/100)
document.bmiForm.bmi.value = finalBmi
if(finalBmi < 19)
{
document.bmiForm.meaning.value = "That you are too thin."
}
if(finalBmi > 19 && finalBmi < 25)
{
document.bmiForm.meaning.value = "That you are healthy."
}
if(finalBmi > 25)
{
document.bmiForm.meaning.value = "That you have overweight."
}
}
else
{
alert("Please Fill in everything correctly")
}
}
//-->
</script>
<form name="bmiForm">
Your Weight(kg): <input type="text" name="weight" size="10"><br />
Your Height(cm): <input type="text" name="height" size="10"><br />
<input type="button" value="Calculate BMI" onClick="calculateBmi()"><br />
Your BMI: <input type="text" name="bmi" size="10"><br />
This Means: <input type="text" name="meaning" size="25"><br />
Your weight should be between: <input type="text" name="weight1" size="10"> to <input type="text" name="weight2" size="10"> kg<br />
<input type="reset" value="Reset" />
</form>
Here, meaning value is displayed by a text input from. But how can I display it as a paragraph, not as a text input?
Thanks in advance for helping.
Note: The meaning will change according to the 3 different categories of results.
It would be very helpful if you please give an example of line of code for the solution.
Instead of using an 'input' tag for meaning, use a 'span' tag, and set the innerHtml of that span to the content you want.

Conditional javascript formula depending on whether checkbox is checked

I have tried a thousand different tutorials and I'm pretty sure my code is correct, yet I can't get this to work. I'm trying to create a calculation that has a different value based on whether the user selects 'yes' or 'no'.
var people = document.getElementById('how-many');
people.onkeyup = function() {
guests = people.value;
if (document.getElementById('leftoversyes').checked) {
feeds = people.value * 2;
} else {
feeds = people.value * 1.5;
}
document.getElementById('turkey-number').innerHTML = guests;
document.getElementById('turkey-weight').innerHTML = feeds;
}
<form id="calculator">
<p>
<label for="how-many">How many people do you plan to feed?</label>
<br />
<input type="text" maxlength="3" name="how-many" id="how-many" />
</p>
<p>
<label for="leftovers">Would you like to have leftovers?</label>
<br />
<input type="checkbox" name="leftoversyes" value="Yes" id="leftoversyes" />Yes
<input type="checkbox" name="leftoversno" value="No" id="leftoversno" />No</p>
<p>
<input type="button" value="Calculate" id="calculate" class="btn" />
<input type="reset" value="clear" id="clearcalculator" />
</p>
</form>
<p>A <span id="turkey-weight"></span>-pound turkey will feed <span id="turkey-number"></span> guests<span id="turkey-leftovers"></span>.</p>
It works in that it will give me the multiply of 1.5, but nothing I do can get it to give me the multiply of 2.
Thanks in advance for the help!
You need to add another listener for when the value of <input type="checkbox" name="leftoversyes" value="Yes" id="leftoversyes" /> changes.
document.getElementById('leftoversyes').onchange = function() {
var guests = document.getElementById('how-many').value;
var feeds;
if (document.getElementById('leftoversyes').checked){
feeds = guests * 2;
} else {
feeds = guests * 1.5;
}
document.getElementById('turkey-number').innerHTML = guests;
document.getElementById('turkey-weight').innerHTML = feeds;
};
Which is identical to the original handler you wrote, so let's refactor it into:
function calculate() {
var guests = document.getElementById('how-many').value;
var feeds;
if (document.getElementById('leftoversyes').checked){
feeds = guests * 2;
} else {
feeds = guests * 1.5;
}
document.getElementById('turkey-number').innerHTML = guests;
document.getElementById('turkey-weight').innerHTML = feeds;
}
document.getElementById('how-many').onkeyup = calculate;
document.getElementById('leftoversyes').onchange = calculate;
Declare feeds variable , use onchange event of #leftovers element to call same function as onkeyup for #people element
var people = document.getElementById('how-many');
var leftovers = document.getElementById('leftoversyes');
function feeder() {
var feeds;
guests = people.value;
if (document.getElementById('leftoversyes').checked){
feeds = people.value * 2;
} else {
feeds = people.value * 1.5;
}
document.getElementById('turkey-number').innerHTML = guests;
document.getElementById('turkey-weight').innerHTML = feeds;
}
people.onkeyup = feeder;
leftovers.onchange = feeder;
<form id="calculator">
<p>
<label for="how-many">How many people do you plan to feed?</label><br />
<input type="text" maxlength="3" name="how-many" id="how-many" />
</p>
<p>
<label for="leftovers">Would you like to have leftovers?</label><br />
<input type="checkbox" name="leftoversyes" value="Yes" id="leftoversyes" /> Yes <input type="checkbox" name="leftoversno" value="No" id="leftoversno" /> No</p>
<p><input type="button" value="Calculate" id="calculate" class="btn" />
<input type="reset" value="clear" id="clearcalculator" /></p>
</form>
<p>A <span id="turkey-weight"></span>-pound turkey will feed <span id="turkey-number"></span> guests<span id="turkey-leftovers"></span>.</p>

Categories